gdk-graphics 0b051eb9b5c1eaa0658babaa4463dd7a80aa9d2c
Loading...
Searching...
No Matches
smart_event.h
1// © Joseph Cameron - All Rights Reserved
2
3#ifndef JFC_SMART_EVENT_H
4#define JFC_SMART_EVENT_H
5
6#include <functional>
7#include <memory>
8#include <mutex>
9#include <unordered_set>
10
11namespace jfc {
14 template<class... event_parameter_types_param>
15 class smart_event final {
16 public:
17 using observer_type = std::function<void(event_parameter_types_param...)>;
18 using observer_weak_ptr_type = std::weak_ptr<observer_type>;
19 using observer_shared_ptr_type = std::shared_ptr<observer_type>;
20
22 [[nodiscard]] observer_shared_ptr_type subscribe(observer_type aObserverFunctor) {
23 auto pObserver = std::make_shared<observer_type>(aObserverFunctor);
24 m_Observers.insert(pObserver);
25 return pObserver;
26 }
27
29 void notify(const event_parameter_types_param&... params) const {
30 std::lock_guard<std::mutex> lock(m_ObserversMutex);
31 for (auto iter = m_Observers.begin(); iter != m_Observers.end(); ) {
32 if (auto observer = iter->lock()) {
33 (*observer)(params...);
34 ++iter;
35 }
36 else {
37 iter = m_Observers.erase(iter);
38 }
39 }
40 }
41
42 smart_event() = default;
43 ~smart_event() = default;
44
45 private:
46 struct observer_weak_ptr_hasher_method {
47 std::size_t operator()(const std::weak_ptr<observer_type>& ptr) const {
48 if (auto sp = ptr.lock()) {
49 return std::hash<std::shared_ptr<observer_type>>{}(sp);
50 }
51 return {};
52 }
53 };
54
55 struct observer_weak_ptr_comparator_method {
56 bool operator()(const std::weak_ptr<observer_type>& lhs, const std::weak_ptr<observer_type>& rhs) const {
57 return !lhs.owner_before(rhs) && !rhs.owner_before(lhs);
58 }
59 };
60 mutable std::unordered_set<observer_weak_ptr_type, observer_weak_ptr_hasher_method, observer_weak_ptr_comparator_method> m_Observers;
61 mutable std::mutex m_ObserversMutex;
62 };
63}
64
65#endif
66
event class that automatically cleans up unused observers
Definition smart_event.h:15
observer_shared_ptr_type subscribe(observer_type aObserverFunctor)
adds an observer
Definition smart_event.h:22
void notify(const event_parameter_types_param &... params) const
notify observers & remove any null observers
Definition smart_event.h:29