Loading...
Searching...
No Matches
MessageManager.h
Go to the documentation of this file.
1//
2// MessageManager.h
3//
4
5#ifndef MALENA_EVENTBUS_H
6#define MALENA_EVENTBUS_H
7
8#include <functional>
9#include <typeindex>
10#include <unordered_map>
11#include <vector>
12#include <tuple>
13#include <algorithm>
14#include <optional>
16
17namespace ml
18{
69 class MessageManager : public DeferredOperationsManager<MessageManager>
70 {
72 using EventKey = std::tuple<std::type_index, int, std::type_index>;
73
74 struct KeyHash
75 {
76 std::size_t operator()(const EventKey& key) const
77 {
78 auto h1 = std::get<0>(key).hash_code();
79 auto h2 = std::hash<int>{}(std::get<1>(key));
80 auto h3 = std::get<2>(key).hash_code();
81 return h1 ^ (h2 << 1) ^ (h3 << 2);
82 }
83 };
84
85 struct Subscription
86 {
87 void* subscriber;
88 std::function<void(const void*)> callback;
89 };
90
91 static std::unordered_map<EventKey, std::vector<Subscription>, KeyHash> subscribers;
92
93 static void doUnsubscribe(const EventKey& key, void* subscriber);
94 static void doUnsubscribeAll(void* subscriber);
96
97 public:
114 template<typename DataType, typename Enum>
115 static void subscribe(Enum event, void* subscriber,
116 std::function<void(const DataType&)> callback);
117
132 template<typename DataType, typename Enum>
133 static void publish(Enum event, const DataType& data);
134
145 template<typename DataType, typename Enum>
146 static void unsubscribe(Enum event, void* subscriber);
147
157 static void unsubscribeAll(void* subscriber);
158
164 static void clear();
165
167
177 static void forceUnsubscribeAll(void* subscriber);
179 };
180
181} // namespace ml
182
183#include "../../../../src/Engine/Messaging/MessageManager.tpp"
184#endif // MALENA_EVENTBUS_H
CRTP base that gives a manager safe deferred-operation support.
Typed, enum-keyed message bus for structured inter-object communication.
static void publish(Enum event, const DataType &data)
Deliver a typed message to all matching subscribers.
static void unsubscribeAll(void *subscriber)
Remove all subscriptions for a given subscriber.
static void subscribe(Enum event, void *subscriber, std::function< void(const DataType &)> callback)
Register a typed callback for a specific enum event.
static void clear()
Remove all subscriptions for all subscribers and all keys.
static void unsubscribe(Enum event, void *subscriber)
Remove one subscriber's callback for a specific typed event.
Definition Component.h:18