|
| 1 | +export module CppUtils.Thread.ScheduledEventDispatcher; |
| 2 | + |
| 3 | +import std; |
| 4 | +import CppUtils.Chrono.Concept; |
| 5 | +import CppUtils.Execution.EventDispatcher; |
| 6 | +import CppUtils.String.Hash; |
| 7 | +import CppUtils.Thread.Scheduler; |
| 8 | + |
| 9 | +export namespace CppUtils::Thread |
| 10 | +{ |
| 11 | + class ScheduledEventDispatcher final |
| 12 | + { |
| 13 | + public: |
| 14 | + using Clock = std::chrono::steady_clock; |
| 15 | + using TimePoint = Clock::time_point; |
| 16 | + |
| 17 | + explicit ScheduledEventDispatcher( |
| 18 | + Scheduler::Clock::duration step = std::chrono::milliseconds(10), |
| 19 | + std::size_t numberThreads = std::thread::hardware_concurrency(), |
| 20 | + std::function<void(std::exception_ptr)> onError = nullptr, |
| 21 | + std::function<void()> finally = nullptr): |
| 22 | + m_scheduler{step, numberThreads, std::move(onError), std::move(finally)} |
| 23 | + {} |
| 24 | + |
| 25 | + template<String::Hasher eventName = String::Hash{}> |
| 26 | + inline auto subscribe(auto&& function) -> void |
| 27 | + { |
| 28 | + m_eventDispatcher.subscribe<eventName>(std::forward<decltype(function)>(function)); |
| 29 | + } |
| 30 | + |
| 31 | + template<String::Hasher eventName = String::Hash{}, class Event = std::nullptr_t, Chrono::Duration Delay = std::chrono::milliseconds> |
| 32 | + inline auto emit(Event&& event = nullptr, Delay delay = std::chrono::milliseconds{0}) -> void |
| 33 | + { |
| 34 | + m_scheduler.schedule([this, event = std::forward<Event>(event)] { |
| 35 | + m_eventDispatcher.emit<eventName>(event); |
| 36 | + }, delay); |
| 37 | + } |
| 38 | + |
| 39 | + template<String::Hasher eventName = String::Hash{}, class Event> |
| 40 | + inline auto emit(Event&& event, TimePoint when) -> void |
| 41 | + { |
| 42 | + m_scheduler.schedule([this, event = std::forward<Event>(event)] { |
| 43 | + m_eventDispatcher.emit<eventName>(event); |
| 44 | + }, when); |
| 45 | + } |
| 46 | + |
| 47 | + inline auto waitUntilFinished() -> void |
| 48 | + { |
| 49 | + m_scheduler.waitUntilFinished(); |
| 50 | + } |
| 51 | + |
| 52 | + private: |
| 53 | + Scheduler m_scheduler; |
| 54 | + Execution::EventDispatcher m_eventDispatcher; |
| 55 | + }; |
| 56 | +} |
0 commit comments