• 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 OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H
17 #define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H
18 #include <list>
19 #include <queue>
20 #include <memory>
21 #include "concurrent_map.h"
22 #include "eventcenter/event.h"
23 #include "visibility.h"
24 namespace OHOS {
25 namespace DistributedData {
26 class EventCenter {
27 public:
28     enum : int32_t {
29         CODE_SYNC = 1,
30         CODE_ASYNC,
31         CODE_INVALID_ARGS,
32     };
33 
34     class Defer final {
35     public:
36         API_EXPORT Defer(std::function<void(const Event &)> handler = nullptr, int32_t evtId = Event::EVT_INVALID);
37         API_EXPORT ~Defer();
38         void *operator new (size_t size) = delete;
39         void *operator new[] (size_t size) = delete;
40         void operator delete (void *) = delete;
41         void operator delete[] (void *) = delete;
42     };
43     API_EXPORT static EventCenter &GetInstance();
44     API_EXPORT bool Subscribe(int32_t evtId, const std::function<void(const Event &)> &observer);
45     API_EXPORT bool Unsubscribe(int32_t evtId);
46     API_EXPORT int32_t PostEvent(std::unique_ptr<Event> evt) const;
47 private:
48     void Dispatch(const Event &evt) const;
49     class AsyncQueue final {
50     public:
51         static constexpr int32_t MAX_CAPABILITY = 100;
52         AsyncQueue &operator++();
53         AsyncQueue &operator--();
54         bool operator<=(int32_t depth) const;
55         void Post(std::unique_ptr<Event> event);
56         void AddHandler(int32_t evtId, std::function<void(const Event &)> handler);
57     private:
58         std::map<int32_t, std::function<void(const Event &)>> handlers_;
59         std::deque<std::unique_ptr<Event>> events_;
60         int32_t depth_ = 0;
61     };
62     ConcurrentMap<int32_t, std::list<std::function<void(const Event &)>>> observers_;
63     static thread_local AsyncQueue *asyncQueue_;
64 };
65 } // namespace DistributedData
66 } // namespace OHOS
67 #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H
68