1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef META_API_PROPERTY_ARRAY_PROPERTY_EVENT_HANDLER_H
17 #define META_API_PROPERTY_ARRAY_PROPERTY_EVENT_HANDLER_H
18
19 #include <meta/api/property/array_property_changes_recognizer.h>
20 #include <meta/api/property/property_event_handler.h>
21 #include <meta/interface/property/array_property.h>
22 #include <meta/interface/simple_event.h>
23
META_BEGIN_NAMESPACE()24 META_BEGIN_NAMESPACE()
25
26 template<typename ValueType>
27 class ArrayPropertyChangedEventHandler {
28 public:
29 ArrayPropertyChangedEventHandler() = default;
30
31 using Property = ArrayProperty<ValueType>;
32 using ArrayChange = ArrayChanges<ValueType>;
33 using FunctionType = void(const ArrayChange&);
34
35 template<typename T>
36 bool Subscribe(const Property& property, T* instance, void (T::*callback)(const ArrayChange&))
37 {
38 changesRecognizer_.SetValue(property);
39 return handler_.Subscribe(
40 property, [=]() { (instance->*callback)(changesRecognizer_.OnArrayPropertyChanged(property)); });
41 }
42
43 bool Subscribe(const Property& property, void (*callback)(const ArrayChange&))
44 {
45 changesRecognizer_.SetValue(property);
46 return handler_.Subscribe(property, [=]() { callback(changesRecognizer_.OnArrayPropertyChanged(property)); });
47 }
48
49 template<typename Func, typename = EnableIfCanInvokeWithArguments<Func, FunctionType>>
50 bool Subscribe(const Property& property, Func func, const ITaskQueue::Ptr& queue = nullptr)
51 {
52 changesRecognizer_.SetValue(property);
53 return handler_.Subscribe(
54 property,
55 [this, property, f = BASE_NS::move(func)]() { f(changesRecognizer_.OnArrayPropertyChanged(property)); },
56 queue);
57 }
58
59 template<typename Func, typename = EnableIfCanInvokeWithArguments<Func, FunctionType>>
60 bool Subscribe(const Property& property, Func func, const BASE_NS::Uid& queueId)
61 {
62 changesRecognizer_.SetValue(property);
63 return handler_.Subscribe(
64 property,
65 [this, property, f = BASE_NS::move(func)]() { f(changesRecognizer_.OnArrayPropertyChanged(property)); },
66 queueId);
67 }
68
69 void Unsubscribe()
70 {
71 handler_.Unsubscribe();
72 changesRecognizer_.Clear();
73 }
74
75 private:
76 ArrayPropertyChangesRecognizer<ValueType> changesRecognizer_;
77 META_NS::PropertyChangedEventHandler handler_;
78 };
79
80 META_END_NAMESPACE()
81
82 #endif
83