1 /* 2 * Copyright (c) 2021 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 FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LISTENER_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LISTENER_H 18 19 #include <unordered_map> 20 21 #include "base/utils/event_callback.h" 22 23 namespace OHOS::Ace { 24 25 template<class T> 26 class ValueListenable { 27 public: 28 using ValueCallback = EventCallback<void(const T&)>; 29 30 ValueListenable() = default; 31 virtual ~ValueListenable() = default; 32 AddListener(const ValueCallback & callback)33 void AddListener(const ValueCallback& callback) 34 { 35 callbacks_.emplace(callback.GetId(), callback); 36 } 37 38 template<class F> AddListener(const F & funcObject)39 typename ValueCallback::IdType AddListener(const F& funcObject) 40 { 41 ValueCallback callback(funcObject); 42 AddListener(callback); 43 return callback.GetId(); 44 } 45 RemoveListener(const ValueCallback & callback)46 void RemoveListener(const ValueCallback& callback) 47 { 48 callbacks_.erase(callback.GetId()); 49 } 50 RemoveListener(typename ValueCallback::IdType id)51 void RemoveListener(typename ValueCallback::IdType id) 52 { 53 callbacks_.erase(id); 54 } 55 ClearListeners()56 void ClearListeners() 57 { 58 callbacks_.clear(); 59 } 60 NotifyListener(const T & value)61 void NotifyListener(const T& value) const 62 { 63 auto callbacks = callbacks_; 64 for (auto&& [id, callback] : callbacks) { 65 if (callback) { 66 callback(value); 67 } 68 } 69 } 70 71 private: 72 std::unordered_map<typename ValueCallback::IdType, ValueCallback> callbacks_; 73 }; 74 75 } // namespace OHOS::Ace 76 77 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LISTENER_H 78