|
| 1 | +#pragma once |
| 2 | +#include <memory> |
| 3 | +#include <mutex> |
| 4 | +#include <vector> |
| 5 | + |
| 6 | +namespace FlowSdk::EventBus { |
| 7 | + |
| 8 | + template<typename EventType> |
| 9 | + class NewEventListener; |
| 10 | + template<typename EventType> |
| 11 | + class NewEventFilter; |
| 12 | + |
| 13 | + template<typename EventType> |
| 14 | + struct EventSubscription { |
| 15 | + std::shared_ptr<NewEventListener<EventType>> listener; |
| 16 | + std::shared_ptr<NewEventFilter<EventType>> filter; |
| 17 | + bool once; |
| 18 | + }; |
| 19 | + |
| 20 | + template<typename EventType> |
| 21 | + class EventStream |
| 22 | + { |
| 23 | + public: |
| 24 | + virtual ~EventStream() = default; |
| 25 | + |
| 26 | + /** |
| 27 | + * Subscribes the given listener to the event stream. |
| 28 | + */ |
| 29 | + void Subscribe(std::shared_ptr<NewEventListener<EventType>> listener) |
| 30 | + { |
| 31 | + Subscribe(listener, nullptr); |
| 32 | + }; |
| 33 | + |
| 34 | + virtual void Subscribe( |
| 35 | + std::shared_ptr<NewEventListener<EventType>> listener, std::shared_ptr<NewEventFilter<EventType>> filter |
| 36 | + ) |
| 37 | + { |
| 38 | + if (listener == nullptr) { |
| 39 | + throw std::invalid_argument("listener cannot be null"); |
| 40 | + } |
| 41 | + |
| 42 | + auto guard = std::lock_guard(mutex); |
| 43 | + subscriptions.push_back(EventSubscription<EventType>{listener, filter, false}); |
| 44 | + }; |
| 45 | + |
| 46 | + /** |
| 47 | + * Subscribes the given listener to the event stream, but only for the next event. |
| 48 | + */ |
| 49 | + virtual void SubscribeOnce(std::shared_ptr<NewEventListener<EventType>> listener) |
| 50 | + { |
| 51 | + SubscribeOnce(listener, nullptr); |
| 52 | + } |
| 53 | + |
| 54 | + virtual void SubscribeOnce( |
| 55 | + std::shared_ptr<NewEventListener<EventType>> listener, std::shared_ptr<NewEventFilter<EventType>> filter |
| 56 | + ) |
| 57 | + { |
| 58 | + if (listener == nullptr) { |
| 59 | + throw std::invalid_argument("listener cannot be null"); |
| 60 | + } |
| 61 | + |
| 62 | + auto guard = std::lock_guard(mutex); |
| 63 | + subscriptions.push_back(EventSubscription<EventType>{listener, filter, true}); |
| 64 | + }; |
| 65 | + |
| 66 | + protected: |
| 67 | + std::mutex mutex; |
| 68 | + |
| 69 | + // All subscriptions to this event stream. |
| 70 | + std::vector<EventSubscription<EventType>> subscriptions; |
| 71 | + }; |
| 72 | +}// namespace FlowSdk::EventBus |
0 commit comments