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 auto iter = observerHandlerMap_.find(what); 45 if (iter == observerHandlerMap_.end()) { 46 TELEPHONY_LOGE("ObserverHandler NotifyObserver %{public}d not register", what); 47 return; 48 } 49 50 for (auto handlers : iter->second) { 51 handlers->SendEvent(what, param, 0); 52 } 53 } 54 55 template<typename T> NotifyObserver(int32_t what,std::shared_ptr<T> object)56 void NotifyObserver(int32_t what, std::shared_ptr<T> object) 57 { 58 auto iter = observerHandlerMap_.find(what); 59 if (iter == observerHandlerMap_.end()) { 60 TELEPHONY_LOGE("ObserverHandler NotifyObserver %{public}d not register", what); 61 return; 62 } 63 for (auto handlers : iter->second) { 64 handlers->SendEvent(what, object); 65 } 66 } 67 68 private: 69 std::unordered_map<int32_t, std::list<std::shared_ptr<AppExecFwk::EventHandler>>> observerHandlerMap_; 70 std::mutex mutex_; 71 }; 72 } // namespace Telephony 73 } // namespace OHOS 74 #endif // OBSERVER_HANDLER_H 75