1 /*
2  * Copyright (C) 2021-2022 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 BASE_OBSERVER_LIST_H
17 #define BASE_OBSERVER_LIST_H
18 
19 #include <list>
20 #include <mutex>
21 #include <memory>
22 #include "base_def.h"
23 
24 template<typename T>
25 class BaseObserverList final {
26 public:
BaseObserverList()27     BaseObserverList(){};
28     ~BaseObserverList();
29 
30     bool Register(T &observer);
31     bool Deregister(T &observer);
32 
33     void ForEach(const std::function<void(T &)> &observer);
34 
35 private:
36     std::mutex lock_ = {};
37     std::list<T *> observers_ = {};
38 
39     BT_DISALLOW_COPY_AND_ASSIGN(BaseObserverList);
40 };
41 
42 template<typename T>
~BaseObserverList()43 BaseObserverList<T>::~BaseObserverList()
44 {
45     std::lock_guard<std::mutex> lock(lock_);
46     observers_.clear();
47 }
48 
49 template<typename T>
Register(T & observer)50 bool BaseObserverList<T>::Register(T &observer)
51 {
52     std::lock_guard<std::mutex> lock(lock_);
53     for (auto it = observers_.begin(); it != observers_.end(); ++it) {
54         if (*it == &observer) {
55             return false;
56         }
57     }
58 
59     observers_.push_back(&observer);
60     return true;
61 }
62 
63 template<typename T>
Deregister(T & observer)64 bool BaseObserverList<T>::Deregister(T &observer)
65 {
66     std::lock_guard<std::mutex> lock(lock_);
67     for (auto it = observers_.begin(); it != observers_.end(); ++it) {
68         if (*it == &observer) {
69             observers_.erase(it);
70             return true;
71         }
72     }
73 
74     return false;
75 }
76 
77 template<typename T>
ForEach(const std::function<void (T &)> & observer)78 void BaseObserverList<T>::ForEach(const std::function<void(T &)> &observer)
79 {
80     std::lock_guard<std::mutex> lock(lock_);
81     for (const auto &it : observers_)
82         observer(*it);
83 }
84 
85 #endif  // BASE_OBSERVER_LIST_H