• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 private:
56     std::mutex mutexForListenersAndEmitByUv_;
57     std::mutex mutexForEmitAndEmitByUv_;
58     std::mutex mutex_;
59     std::list<EventListener> listeners_;
60     void *data_;
61     std::atomic_bool isValid_;
62 };
63 
64 struct UvWorkWrapper {
65     UvWorkWrapper() = delete;
66     explicit UvWorkWrapper(void *theData, napi_env theEnv, std::string eventType, EventManager *eventManager);
67     void *data;
68     napi_env env;
69     std::string type;
70     EventManager *manager;
71 };
72 } // namespace NetManagerStandard
73 } // namespace OHOS
74 #endif // COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H
75