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 <list> 20 #include <mutex> 21 #include <string> 22 #include <functional> 23 #include "js_common.h" 24 #include "cj_request_ffi.h" 25 26 namespace OHOS::CJSystemapi::Request { 27 using OHOS::Request::SubscribeType; 28 using OHOS::Request::ExceptionErrorCode; 29 using OHOS::Request::NotifyData; 30 31 using CFunc = void *; 32 using ProgressOnCallBackType = std::function<void(CProgress)>; 33 34 class ListenerList { 35 public: ListenerList(const std::string & taskId,const SubscribeType & type)36 ListenerList(const std::string &taskId, const SubscribeType &type) 37 : taskId_(taskId), type_(type) 38 { 39 } 40 bool HasListener(); 41 struct CallBackInfo { 42 ProgressOnCallBackType cb_; 43 CFunc cbId_ = nullptr; 44 CallBackInfoCallBackInfo45 CallBackInfo(ProgressOnCallBackType cb, CFunc cbId) 46 : cb_(cb), cbId_(cbId) {} 47 }; 48 49 protected: 50 bool IsListenerAdded(void *cb); 51 void OnMessageReceive(const std::shared_ptr<NotifyData> ¬ifyData); 52 void AddListenerInner(ProgressOnCallBackType &cb, CFunc cbId); 53 void RemoveListenerInner(CFunc cb); 54 55 protected: 56 const std::string taskId_; 57 const SubscribeType type_; 58 59 std::recursive_mutex allCbMutex_; 60 std::list<std::pair<bool, std::shared_ptr<CallBackInfo>>> allCb_; 61 std::atomic<uint32_t> validCbNum{ 0 }; 62 }; 63 } // namespace OHOS::CJSystemapi::Request 64 #endif // OHOS_REQUEST_CJ_LISTENER_LIST_H 65