contur2
Loading...
Searching...
No Matches
event.h
Go to the documentation of this file.
1
7
8#pragma once
9
10#include <algorithm>
11#include <functional>
12#include <vector>
13
14#include "contur/core/types.h"
15
16namespace contur {
17
31 template <typename... Args> class Event
32 {
33 public:
35 using Callback = std::function<void(Args...)>;
36
37 Event() = default;
38 ~Event() = default;
39
40 // Non-copyable (subscriptions are identity-bound)
41 Event(const Event &) = delete;
42 Event &operator=(const Event &) = delete;
43
44 // Movable
45 Event(Event &&) noexcept = default;
46 Event &operator=(Event &&) noexcept = default;
47
51 [[nodiscard]] SubscriptionId subscribe(Callback callback)
52 {
53 auto id = nextId_++;
54 subscribers_.push_back({id, std::move(callback)});
55 return id;
56 }
57
62 {
63 auto it = std::find_if(subscribers_.begin(), subscribers_.end(), [id](const Subscriber &s) {
64 return s.id == id;
65 });
66 if (it != subscribers_.end())
67 {
68 subscribers_.erase(it);
69 return true;
70 }
71 return false;
72 }
73
76 void emit(Args... args) const
77 {
78 for (const auto &sub : subscribers_)
79 {
80 sub.callback(args...);
81 }
82 }
83
85 [[nodiscard]] std::size_t subscriberCount() const noexcept
86 {
87 return subscribers_.size();
88 }
89
91 void clear()
92 {
93 subscribers_.clear();
94 }
95
96 private:
102
103 std::vector<Subscriber> subscribers_;
105 };
106
107} // namespace contur
SubscriptionId nextId_
Definition event.h:104
Event & operator=(const Event &)=delete
SubscriptionId subscribe(Callback callback)
Registers a callback to be invoked when the event fires.
Definition event.h:51
~Event()=default
std::size_t subscriberCount() const noexcept
Returns the number of active subscribers.
Definition event.h:85
Event()=default
void emit(Args... args) const
Fires the event, invoking all registered callbacks with the given arguments.
Definition event.h:76
void clear()
Removes all subscribers.
Definition event.h:91
std::function< void(Args...)> Callback
The callback signature for subscribers.
Definition event.h:35
std::vector< Subscriber > subscribers_
Definition event.h:103
Event(Event &&) noexcept=default
bool unsubscribe(SubscriptionId id)
Removes a previously registered subscription.
Definition event.h:61
Event(const Event &)=delete
Definition block.h:15
std::uint64_t SubscriptionId
Unique identifier for an event subscription.
Definition types.h:27
SubscriptionId id
Definition event.h:99
Common type aliases, sentinel constants, and forward declarations used throughout the Contur 2 kernel...