Line data Source code
1 : // Webthing-CPP
2 : // SPDX-FileCopyrightText: 2023-present Benno Waldhauer
3 : // SPDX-License-Identifier: MIT
4 :
5 : #pragma once
6 :
7 : #include <functional>
8 : #include <optional>
9 :
10 : namespace bw::webthing {
11 :
12 : template<class T>
13 : class Value
14 : {
15 : public:
16 : typedef std::function<void (const T&)> ValueForwarder;
17 : typedef std::function<void (const T&)> ValueChangedCallback;
18 :
19 32 : Value(std::optional<T> initial_value = std::nullopt, ValueForwarder value_forwarder = nullptr)
20 32 : : last_value(initial_value)
21 32 : , value_forwarder(value_forwarder)
22 : {
23 32 : }
24 :
25 33 : void set(T value)
26 : {
27 33 : if (value_forwarder)
28 12 : value_forwarder(value);
29 33 : notify_of_external_update(value);
30 33 : }
31 :
32 131 : std::optional<T> get() const
33 : {
34 131 : return last_value;
35 : }
36 :
37 36 : void notify_of_external_update(T value)
38 : {
39 36 : if (last_value != value)
40 : {
41 34 : last_value = value;
42 34 : notify_observers(value);
43 : }
44 36 : }
45 :
46 29 : void add_observer(ValueChangedCallback observer)
47 : {
48 29 : observers.push_back(observer);
49 29 : }
50 :
51 : private:
52 :
53 34 : void notify_observers(T value)
54 : {
55 67 : for (auto& observer : observers)
56 : {
57 33 : observer(value);
58 : }
59 34 : }
60 :
61 : std::optional<T> last_value;
62 : ValueForwarder value_forwarder;
63 : std::vector<ValueChangedCallback> observers;
64 : };
65 :
66 : } // bw::webthing
|