blob: f79bcc77b50c217ba5deb94d5a5016c02757d17c [file] [log] [blame]
Krzysztof Grobelnye6d48872022-02-08 13:41:30 +01001#pragma once
2
3#include <boost/asio.hpp>
4
5#include <any>
6
7namespace utils
8{
9
10class MessangerService : public boost::asio::execution_context::service
11{
12 public:
13 using key_type = MessangerService;
14
15 struct Context
16 {
17 std::vector<std::any> handlers;
18 };
19
20 MessangerService(boost::asio::execution_context& execution_context);
21 ~MessangerService() = default;
22
Patrick Williams3a1c2972023-05-10 07:51:04 -050023 void shutdown() {}
Krzysztof Grobelnye6d48872022-02-08 13:41:30 +010024
25 Context& create();
26 void destroy(Context& context);
27
28 template <class T>
29 void send(const T& event)
30 {
31 using HandlerType = std::function<void(const T&)>;
32
33 for (const auto& context : contexts_)
34 {
35 for (const auto& any : context->handlers)
36 {
37 if (const HandlerType* handler =
38 std::any_cast<HandlerType>(&any))
39 {
40 (*handler)(event);
41 }
42 }
43 }
44 }
45
46 static boost::asio::execution_context::id id;
47
48 private:
49 std::vector<std::unique_ptr<Context>> contexts_;
50};
51
52} // namespace utils