yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
event_bus.h
Go to the documentation of this file.
1#ifndef YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
2#define YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
3
4#include <functional>
5#include <typeindex>
6#include <unordered_map>
7#include <vector>
8#include <memory>
9#include <algorithm>
10
11namespace yaze {
12
13struct Event {
14 virtual ~Event() = default;
15};
16
17class EventBus {
18public:
19 using HandlerId = size_t;
20
21 template<typename T>
22 HandlerId Subscribe(std::function<void(const T&)> handler) {
23 static_assert(std::is_base_of<Event, T>::value, "T must derive from Event");
24 auto type_idx = std::type_index(typeid(T));
25 auto wrapper = [handler](const Event& e) {
26 handler(static_cast<const T&>(e));
27 };
28
29 size_t id = next_id_++;
30 handlers_[type_idx].push_back({id, wrapper});
31 return id;
32 }
33
34 template<typename T>
35 void Publish(const T& event) {
36 static_assert(std::is_base_of<Event, T>::value, "T must derive from Event");
37 auto type_idx = std::type_index(typeid(T));
38 if (handlers_.find(type_idx) != handlers_.end()) {
39 for (const auto& handler : handlers_[type_idx]) {
40 handler.fn(event);
41 }
42 }
43 }
44
46 for (auto& [type, list] : handlers_) {
47 auto it = std::remove_if(list.begin(), list.end(),
48 [id](const HandlerEntry& entry) { return entry.id == id; });
49 if (it != list.end()) {
50 list.erase(it, list.end());
51 return;
52 }
53 }
54 }
55
56private:
57 struct HandlerEntry {
59 std::function<void(const Event&)> fn;
60 };
61
62 std::unordered_map<std::type_index, std::vector<HandlerEntry>> handlers_;
64};
65
66} // namespace yaze
67
68#endif // YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
void Publish(const T &event)
Definition event_bus.h:35
void Unsubscribe(HandlerId id)
Definition event_bus.h:45
HandlerId Subscribe(std::function< void(const T &)> handler)
Definition event_bus.h:22
HandlerId next_id_
Definition event_bus.h:63
size_t HandlerId
Definition event_bus.h:19
std::unordered_map< std::type_index, std::vector< HandlerEntry > > handlers_
Definition event_bus.h:62
std::function< void(const Event &) fn)
Definition event_bus.h:59
virtual ~Event()=default