Molybden
Loading...
Searching...
No Matches
subscription_impl.hpp
1// Copyright (c) 2000-2023 TeamDev Ltd. All rights reserved.
2// TeamDev PROPRIETARY and CONFIDENTIAL.
3// Use is subject to license terms.
4
5#ifndef MOLYBDEN_SUBSCRIPTION_IMPL_HPP
6#define MOLYBDEN_SUBSCRIPTION_IMPL_HPP
7
8#include <algorithm>
9#include <functional>
10#include <utility>
11#include <vector>
12
13#include "molybden/base/subscription.hpp"
14
15namespace molybden {
16namespace internal {
17
18class SubscriptionObserver {
19 public:
20 virtual ~SubscriptionObserver() = default;
21
22 virtual void onCanceled(int32_t id){};
23};
24
25template <typename T>
26class SubscriptionImpl : public Subscription {
27 public:
28 SubscriptionImpl(int32_t id, std::function<void(const T& e)> observer);
29
30 void notify(const T& event);
31
32 void cancel() override;
33
34 void addObserver(SubscriptionObserver* observer);
35
36 void removeObserver(SubscriptionObserver* observer);
37
38 private:
39 int32_t id_;
40 std::function<void(const T& e)> observer_;
41
42 std::vector<SubscriptionObserver*> observers_;
43};
44
45template <typename T>
46SubscriptionImpl<T>::SubscriptionImpl(int32_t id,
47 std::function<void(const T&)> observer)
48 : id_(id), observer_(std::move(observer)) {}
49
50template <typename T>
51void SubscriptionImpl<T>::notify(const T& event) {
52 if (observer_) {
53 observer_(event);
54 }
55}
56
57template <typename T>
58void SubscriptionImpl<T>::cancel() {
59 observer_ = {};
60 for (auto* observer : observers_) {
61 observer->onCanceled(id_);
62 }
63}
64
65template <typename T>
66void SubscriptionImpl<T>::addObserver(SubscriptionObserver* observer) {
67 observers_.push_back(observer);
68}
69
70template <typename T>
71void SubscriptionImpl<T>::removeObserver(SubscriptionObserver* observer) {
72 auto it = std::find(observers_.begin(), observers_.end(), observer);
73 if (it != observers_.end()) {
74 observers_.erase(it);
75 }
76}
77
78} // namespace internal
79} // namespace molybden
80
81#endif // MOLYBDEN_SUBSCRIPTION_IMPL_HPP
virtual void cancel()=0
Cancels this subscription.