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