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_CORE_ANIMATION_SPRING_NODE_LISTENABLE_H
17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_ANIMATION_SPRING_NODE_LISTENABLE_H
18 
19 #include <unordered_map>
20 
21 #include "base/utils/event_callback.h"
22 #include "base/utils/utils.h"
23 
24 namespace OHOS::Ace {
25 
26 class SpringNodeListenable {
27 public:
28     using UpdateCallback = EventCallback<void(const double&, const double&)>; // value and velocity
29 
AddUpdateListener(const UpdateCallback & callback)30     void AddUpdateListener(const UpdateCallback& callback)
31     {
32         updateCallbacks_.emplace(callback.GetId(), callback);
33     }
34 
35     template<class F>
AddUpdateListener(const F & funcObject)36     UpdateCallback::IdType AddUpdateListener(const F& funcObject)
37     {
38         UpdateCallback callback(funcObject);
39         AddUpdateListener(callback);
40         return callback.GetId();
41     }
42 
NotifyUpdateListener(double value,double velocity)43     void NotifyUpdateListener(double value, double velocity) const
44     {
45         for (auto&& [id, callback] : updateCallbacks_) {
46             if (callback) {
47                 callback(value, velocity);
48             }
49         }
50     }
51 
RemoveUpdateListener(typename UpdateCallback::IdType id)52     void RemoveUpdateListener(typename UpdateCallback::IdType id)
53     {
54         updateCallbacks_.erase(id);
55     }
56 
57 private:
58     std::unordered_map<UpdateCallback::IdType, UpdateCallback> updateCallbacks_;
59 };
60 
61 } // namespace OHOS::Ace
62 
63 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_ANIMATION_SPRING_NODE_LISTENABLE_H
64