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