Health-GPS 3.0.0.0
Global Health Policy Simulation model (Health-GPS)
Loading...
Searching...
No Matches
event_bus.h
Go to the documentation of this file.
1#pragma once
2
3#include "event_subscriber.h"
4#include <functional>
5#include <memory>
6#include <mutex>
7#include <shared_mutex>
8#include <unordered_map>
9
10namespace hgps {
11
13class DefaultEventBus final : public EventAggregator {
14 public:
15 [[nodiscard]] std::unique_ptr<EventSubscriber>
16 subscribe(EventType event_id,
17 std::function<void(std::shared_ptr<EventMessage> message)> function) override;
18
19 void publish(std::unique_ptr<EventMessage> message) const override;
20
21 void publish_async(std::unique_ptr<EventMessage> message) const override;
22
23 bool unsubscribe(const EventSubscriber &subscriber) override;
24
27 [[nodiscard]] std::size_t count();
28
30 void clear() noexcept;
31
32 private:
33 using mutex_type = std::shared_mutex;
34 mutable mutex_type subscribe_mutex_;
35 std::unordered_multimap<int, std::string> registry_;
36 std::unordered_map<std::string, std::function<void(std::shared_ptr<EventMessage>)>>
37 subscribers_;
38
39 template <typename Callable> void shared_access(const Callable &callable) const {
40 try {
41 std::shared_lock<mutex_type> lock(subscribe_mutex_);
42 callable();
43 } catch (std::system_error &) {
44 // do nothing
45 }
46 }
47
48 template <typename Callable> void exclusive_access(const Callable &callable) const {
49 try {
50 std::unique_lock<mutex_type> lock(subscribe_mutex_);
51 callable();
52 } catch (std::system_error &) {
53 // do nothing
54 }
55 }
56};
57} // namespace hgps
Implements the default memory-based simulation event bus type.
Definition event_bus.h:13
void publish_async(std::unique_ptr< EventMessage > message) const override
Publishes a message to all subscribers asynchronous.
Definition event_bus.cpp:33
void clear() noexcept
Clear all registered subscribers.
Definition event_bus.cpp:67
std::unique_ptr< EventSubscriber > subscribe(EventType event_id, std::function< void(std::shared_ptr< EventMessage > message)> function) override
Subscribes a handler function to an event type identifier.
Definition event_bus.cpp:8
bool unsubscribe(const EventSubscriber &subscriber) override
Unsubscribes from an event notification.
Definition event_bus.cpp:38
std::size_t count()
Gets the number of registered subscribers.
Definition event_bus.cpp:60
void publish(std::unique_ptr< EventMessage > message) const override
Publishes a message to all subscribers synchronous.
Definition event_bus.cpp:21
Defines the event aggregator interface type.
Definition event_aggregator.h:59
Defines the event subscriber interface type.
Definition event_aggregator.h:37
Top-level namespace for Health-GPS Console host application.
Definition command_options.cpp:8
EventType
Event Message type enumeration.
Definition event_message.h:10