1 /* 2 * Copyright (c) 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 COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H 17 #define COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H 18 19 #include <atomic> 20 #include <list> 21 #include <mutex> 22 23 #include <uv.h> 24 25 #include "event_listener.h" 26 27 namespace OHOS { 28 namespace NetManagerStandard { 29 class EventManager { 30 public: 31 EventManager(); 32 33 void AddListener(napi_env env, const std::string &type, napi_value callback, bool once, bool asyncCallback); 34 void DeleteListener(const std::string &type, napi_value callback); 35 void Emit(const std::string &type, const std::pair<napi_value, napi_value> &argv); 36 void SetData(void *data); 37 void EmitByUv(const std::string &type, void *data, void(handler)(uv_work_t *, int status)); 38 bool HasEventListener(const std::string &type); 39 void DeleteListener(const std::string &type); 40 void DeleteAllListener(); 41 [[nodiscard]] void *GetData(); 42 IsListenerListEmpty()43 bool IsListenerListEmpty() const 44 { 45 return listeners_.empty(); 46 } 47 GetListenerListNum()48 size_t GetListenerListNum() const 49 { 50 return listeners_.size(); 51 } 52 bool IsValid() const; 53 void SetInvalid(); 54 55 napi_ref GetRef() const; 56 void SetRef(napi_ref ref); 57 58 private: 59 std::mutex mutexForListenersAndEmitByUv_; 60 std::mutex mutexForEmitAndEmitByUv_; 61 std::mutex mutex_; 62 std::list<EventListener> listeners_; 63 void *data_ = nullptr; 64 std::atomic_bool isValid_; 65 napi_ref ref_ = nullptr; 66 }; 67 68 struct UvWorkWrapper { 69 UvWorkWrapper() = delete; 70 explicit UvWorkWrapper(void *theData, napi_env theEnv, std::string eventType, EventManager *eventManager); 71 void *data; 72 napi_env env; 73 std::string type; 74 EventManager *manager; 75 }; 76 } // namespace NetManagerStandard 77 } // namespace OHOS 78 #endif // COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H 79