MayaFlux 0.1.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
EventBus.cpp
Go to the documentation of this file.
1#include "EventBus.hpp"
2
3namespace Lila {
4
5StreamEvent::StreamEvent(EventType t, EventData d)
6 : type(t)
7 , data(std::move(d))
8 , timestamp(std::chrono::system_clock::now())
9{
10}
11
12void EventBus::subscribe(EventType type, const std::shared_ptr<Subscription>& subscriber)
13{
14 std::lock_guard lock(m_mutex);
15 m_subscribers[type].emplace_back(subscriber);
16}
17
19{
20 std::vector<std::shared_ptr<Subscription>> active_subscribers;
21
22 {
23 std::lock_guard lock(m_mutex);
24 auto it = m_subscribers.find(event.type);
25 if (it == m_subscribers.end())
26 return;
27
28 auto& subscribers = it->second;
29 subscribers.erase(
30 std::remove_if(subscribers.begin(), subscribers.end(),
31 [&active_subscribers](const std::weak_ptr<Subscription>& weak) {
32 if (auto shared = weak.lock()) {
33 active_subscribers.push_back(shared);
34 return false;
35 }
36 return true;
37 }),
38 subscribers.end());
39 }
40
41 for (auto& subscriber : active_subscribers) {
42 subscriber->on_event(event);
43 }
44}
45
46}
std::mutex m_mutex
Mutex for thread safety.
Definition EventBus.hpp:183
std::unordered_map< EventType, std::vector< std::weak_ptr< Subscription > > > m_subscribers
Subscribers by event type.
Definition EventBus.hpp:182
void subscribe(EventType type, const std::shared_ptr< Subscription > &subscriber)
Subscribe to an event type with a Subscription object.
Definition EventBus.cpp:12
void publish(const StreamEvent &event)
Publish an event to all subscribers of its type.
Definition EventBus.cpp:18
EventType type
Type of event.
Definition EventBus.hpp:122
StreamEvent(EventType t, EventData d=std::monostate {})
Definition EventBus.cpp:5
Represents a published event in the system.
Definition EventBus.hpp:121