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_REGISTRY_EVENT_BUS_H_
2#define YAZE_APP_EDITOR_REGISTRY_EVENT_BUS_H_
3
4#include <algorithm>
5#include <functional>
6#include <memory>
7#include <typeindex>
8#include <unordered_map>
9#include <vector>
10
11namespace yaze {
12
13struct Event {
14 virtual ~Event() = default;
15};
16
17class EventBus {
18 public:
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(
48 list.begin(), list.end(),
49 [id](const HandlerEntry& entry) { return entry.id == id; });
50 if (it != list.end()) {
51 list.erase(it, list.end());
52 return;
53 }
54 }
55 }
56
57 private:
58 struct HandlerEntry {
60 std::function<void(const Event&)> fn;
61 };
62
63 std::unordered_map<std::type_index, std::vector<HandlerEntry>> handlers_;
65};
66
67} // namespace yaze
68
69#endif // YAZE_APP_EDITOR_REGISTRY_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:64
size_t HandlerId
Definition event_bus.h:19
std::unordered_map< std::type_index, std::vector< HandlerEntry > > handlers_
Definition event_bus.h:63
std::function< void(const Event &) fn)
Definition event_bus.h:60
virtual ~Event()=default