• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 OBSERVER_HANDLER_H
17 #define OBSERVER_HANDLER_H
18 
19 #include <mutex>
20 #include <unordered_map>
21 #include "event_handler.h"
22 #include "telephony_log_wrapper.h"
23 
24 namespace OHOS {
25 namespace Telephony {
26 class ObserverHandler {
27 public:
28     ObserverHandler();
29 
30     virtual ~ObserverHandler();
31 
32     void RegObserver(int32_t what, const std::shared_ptr<AppExecFwk::EventHandler> handler);
33 
34     void RegUniqueObserver(int32_t what, const std::shared_ptr<AppExecFwk::EventHandler> handler);
35 
36     void Remove(int32_t what, const std::shared_ptr<AppExecFwk::EventHandler> handler);
37 
38     void RemoveAll();
39 
40     void NotifyObserver(int32_t what);
41 
NotifyObserver(int32_t what,int64_t param)42     void NotifyObserver(int32_t what, int64_t param)
43     {
44         std::lock_guard<std::mutex> lock(mutex_);
45         auto iter = observerHandlerMap_.find(what);
46         if (iter == observerHandlerMap_.end()) {
47             TELEPHONY_LOGE("ObserverHandler NotifyObserver %{public}d not register", what);
48             return;
49         }
50 
51         for (auto handlers : iter->second) {
52             handlers->SendEvent(what, param, 0);
53         }
54     }
55 
56     template<typename T>
NotifyObserver(int32_t what,std::shared_ptr<T> object)57     void NotifyObserver(int32_t what, std::shared_ptr<T> object)
58     {
59         std::lock_guard<std::mutex> lock(mutex_);
60         auto iter = observerHandlerMap_.find(what);
61         if (iter == observerHandlerMap_.end()) {
62             TELEPHONY_LOGE("ObserverHandler NotifyObserver %{public}d not register", what);
63             return;
64         }
65         for (auto handlers : iter->second) {
66             handlers->SendEvent(what, object);
67         }
68     }
69 
70 private:
71     std::unordered_map<int32_t, std::list<std::shared_ptr<AppExecFwk::EventHandler>>> observerHandlerMap_;
72     std::mutex mutex_;
73 };
74 } // namespace Telephony
75 } // namespace OHOS
76 #endif // OBSERVER_HANDLER_H
77