1 /*
2  * Copyright (c) 2024 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 SUBSCRIBER_H
17 #define SUBSCRIBER_H
18 
19 #include "ffi_remote_data.h"
20 #include "common_event_defination.h"
21 
22 #include "common_event_subscribe_info.h"
23 #include "common_event_subscriber.h"
24 
25 namespace OHOS::CommonEventManager {
26     using CommonEventSubscribeInfo = OHOS::EventFwk::CommonEventSubscribeInfo;
27     using CommonEventSubscriber = OHOS::EventFwk::CommonEventSubscriber;
28     using CommonEventData = OHOS::EventFwk::CommonEventData;
29 
30     class SubscriberImpl : public CommonEventSubscriber {
31     public:
32         SubscriberImpl(std::shared_ptr<CommonEventSubscribeInfo> sp, int64_t infoId);
33         ~SubscriberImpl() override;
34 
35         void OnReceiveEvent(const CommonEventData &data) override;
36 
37         unsigned long long GetID();
38 
39         int64_t GetSubscribeInfoId();
40 
41         void SetSubscriberManagerId(int64_t id);
42 
43         int64_t GetSubscriberManagerId();
44 
45         void SetCallback(const std::function<void(CCommonEventData)> &callback);
46 
47     private:
48         std::function<void(CCommonEventData)> callback_;
49         std::shared_ptr<bool> valid_;
50         std::atomic_ullong id_;
51         static std::atomic_ullong subscriberID_;
52         int64_t infoId_;
53         int64_t managerId_ = -1;
54     };
55 
56     class SubscriberManager : public OHOS::FFI::FFIData {
57     public:
GetRuntimeType()58         OHOS::FFI::RuntimeType *GetRuntimeType() override
59         {
60             return GetClassType();
61         }
62         SubscriberManager(std::shared_ptr<CommonEventSubscribeInfo> info, int64_t infoId);
63         ~SubscriberManager() override;
64 
65         std::shared_ptr<SubscriberImpl> GetSubscriber();
66 
67         int64_t GetSubscribeInfoId();
68 
69     private:
70         friend class OHOS::FFI::RuntimeType;
71         friend class OHOS::FFI::TypeBase;
GetClassType()72         static OHOS::FFI::RuntimeType *GetClassType()
73         {
74             static OHOS::FFI::RuntimeType runtimeType =
75                 OHOS::FFI::RuntimeType::Create<OHOS::FFI::FFIData>("SubscriberManager");
76             return &runtimeType;
77         }
78         std::shared_ptr<SubscriberImpl> subscriber;
79     };
80 
81 } // namespace OHOS::CommonEventManager
82 
83 #endif // SUBSCRIBER_H
84