12#include <unordered_map>
34 template <
typename Event>
35 using Handler = std::function<void(
const Event&)>;
40 template <
typename Event>
43 handlers_[std::type_index{
typeid(Event)}].push_back(
44 std::make_shared<TypedSubscription<Event>>(
id, std::move(handler)));
52 for (
auto& [type, subscriptions] : handlers_) {
53 const auto found = std::ranges::find(subscriptions,
id, &Subscription::id_of);
54 if (found != subscriptions.end()) {
55 (*found)->deactivate();
56 subscriptions.erase(found);
65 template <
typename Event>
67 const auto found = handlers_.find(std::type_index{
typeid(Event)});
68 if (found == handlers_.end() || found->second.empty()) {
71 const std::vector<std::shared_ptr<Subscription>> subscriptions = found->second;
72 for (
const auto& subscription : subscriptions) {
73 if (subscription->active()) {
74 dynamic_cast<const TypedSubscription<Event>&
>(*subscription).call(event);
81 template <
typename Event>
83 const auto found = handlers_.find(std::type_index{
typeid(Event)});
84 return found == handlers_.end() ? 0 : found->second.size();
89 for (
auto& [type, subscriptions] : handlers_) {
90 for (
const auto& subscription : subscriptions) {
91 subscription->deactivate();
101 Subscription(
const Subscription&) =
delete;
102 Subscription& operator=(
const Subscription&) =
delete;
103 Subscription(Subscription&&) =
delete;
104 Subscription& operator=(Subscription&&) =
delete;
105 virtual ~Subscription() =
default;
107 [[nodiscard]]
static SubscriptionId id_of(
const std::shared_ptr<Subscription>& self) {
111 [[nodiscard]]
bool active() const noexcept {
return active_; }
113 void deactivate() noexcept { active_ =
false; }
120 template <
typename Event>
121 class TypedSubscription final :
public Subscription {
124 : Subscription{id}, handler_{
std::move(handler)} {}
126 void call(
const Event& event)
const { handler_(event); }
129 Handler<Event> handler_;
132 std::unordered_map<std::type_index, std::vector<std::shared_ptr<Subscription>>> handlers_;
Lets systems react to events without knowing who sends them.
Definition event_bus.hpp:31
std::function< void(const Event &)> Handler
Callback for events of type Event.
Definition event_bus.hpp:35
std::size_t subscriber_count() const
Number of handlers registered for events of type Event.
Definition event_bus.hpp:82
SubscriptionId subscribe(Handler< Event > handler)
Registers a handler for events of type Event.
Definition event_bus.hpp:41
void publish(const Event &event)
Calls every handler of type Event with event, before returning.
Definition event_bus.hpp:66
bool unsubscribe(SubscriptionId id)
Removes a handler.
Definition event_bus.hpp:51
void clear()
Removes every handler of every event type.
Definition event_bus.hpp:88
Logging, time, main loop, events and configuration shared by client and server.
Definition clock.hpp:11
std::uint64_t SubscriptionId
Handle returned by EventBus::subscribe(), used to unsubscribe. Never 0.
Definition event_bus.hpp:19
Definition endpoint.hpp:85