Back to Site
Loading...
Searching...
No Matches
event_bus.h
Go to the documentation of this file.
1#pragma once
2
30#include <functional>
31#include <mutex>
32#include <typeindex>
33#include <typeinfo>
34#include <unordered_map>
35#include <utility>
36#include <vector>
37
38namespace librats {
39
40class EventBus {
41public:
44 template <class E>
45 void on(std::function<void(const E&)> handler) {
46 std::lock_guard<std::mutex> lock(mutex_);
47 handlers_[std::type_index(typeid(E))].push_back(
48 [h = std::move(handler)](const void* e) { h(*static_cast<const E*>(e)); });
49 }
50
52 template <class E>
53 void emit(const E& event) {
54 std::vector<ErasedHandler> snapshot;
55 {
56 std::lock_guard<std::mutex> lock(mutex_);
57 auto it = handlers_.find(std::type_index(typeid(E)));
58 if (it == handlers_.end()) return;
59 snapshot = it->second; // copy under lock, then invoke unlocked
60 }
61 for (auto& h : snapshot) h(&event);
62 }
63
64private:
65 using ErasedHandler = std::function<void(const void*)>;
66 std::mutex mutex_;
67 std::unordered_map<std::type_index, std::vector<ErasedHandler>> handlers_;
68};
69
70} // namespace librats
void emit(const E &event)
Publish an event to every handler registered for its type.
Definition event_bus.h:53
void on(std::function< void(const E &)> handler)
Register a handler for events of type E.
Definition event_bus.h:45
Definition node.h:65