• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 OHOS_REQUEST_CJ_LISTENER_LIST_H
17 #define OHOS_REQUEST_CJ_LISTENER_LIST_H
18 
19 #include <functional>
20 #include <list>
21 #include <mutex>
22 #include <string>
23 #include "cj_request_ffi.h"
24 #include "js_common.h"
25 
26 namespace OHOS::CJSystemapi::Request {
27 using OHOS::Request::NotifyData;
28 using OHOS::Request::Response;
29 using OHOS::Request::SubscribeType;
30 
31 using CFunc = void *;
32 
33 class ListenerList {
34 public:
ListenerList(const std::string & taskId,const SubscribeType & type)35     ListenerList(const std::string &taskId, const SubscribeType &type) : taskId_(taskId), type_(type)
36     {
37     }
38     bool HasListener();
39     struct CallBackInfo {
40         std::function<void(CProgress)> progressCB_;
41         std::function<void(CResponse)> responseCB_;
42         CFunc cbId_ = nullptr;
43 
CallBackInfoCallBackInfo44         CallBackInfo(std::function<void(CProgress)> cb, CFunc cbId) : progressCB_(cb), cbId_(cbId) {}
45 
CallBackInfoCallBackInfo46         CallBackInfo(std::function<void(CResponse)> cb, CFunc cbId) : responseCB_(cb), cbId_(cbId) {}
47     };
48 
49 protected:
50     bool IsListenerAdded(void *cb);
51     void OnMessageReceive(const std::shared_ptr<NotifyData> &notifyData);
52     void OnMessageReceive(const std::shared_ptr<Response> &response);
53     void AddListenerInner(std::function<void(CProgress)> &cb, CFunc cbId);
54     void AddListenerInner(std::function<void(CResponse)> &cb, CFunc cbId);
55     void RemoveListenerInner(CFunc cb);
56 
57 protected:
58     const std::string taskId_;
59     const SubscribeType type_;
60 
61     std::recursive_mutex allCbMutex_;
62     std::list<std::pair<bool, std::shared_ptr<CallBackInfo>>> allCb_;
63     std::atomic<uint32_t> validCbNum{0};
64 };
65 } // namespace OHOS::CJSystemapi::Request
66 #endif // OHOS_REQUEST_CJ_LISTENER_LIST_H
67