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 #include "js_observer.h"
17 
18 namespace OHOS::DistributedData {
Clear()19 void JSObserver::Clear()
20 {
21     // Clear() run in js main thread, so it serial run with AsyncCall() lambda, so we can use no lock.
22     if (callback_ == nullptr) {
23         return ;
24     }
25     napi_delete_reference(uvQueue_->GetEnv(), callback_);
26     callback_ = nullptr;
27 }
28 
JSObserver(std::shared_ptr<UvQueue> uvQueue,napi_value callback)29 JSObserver::JSObserver(std::shared_ptr<UvQueue> uvQueue, napi_value callback)
30     : uvQueue_(uvQueue)
31 {
32     napi_create_reference(uvQueue_->GetEnv(), callback, 1, &callback_);
33 }
34 
~JSObserver()35 JSObserver::~JSObserver()
36 {
37 }
38 
GetCallback()39 napi_ref JSObserver::GetCallback()
40 {
41     return callback_;
42 }
43 
AsyncCall(UvQueue::NapiArgsGenerator genArgs)44 void JSObserver::AsyncCall(UvQueue::NapiArgsGenerator genArgs)
45 {
46     if (callback_ == nullptr) {
47         return;
48     }
49 
50     uvQueue_->AsyncCall([observer = shared_from_this()](napi_env env) -> napi_value {
51         // the lambda run in js main thread, so it serial run with Clear(), so we can use no lock.
52         if (observer->callback_ == nullptr) {
53             return nullptr;
54         }
55         napi_value callback = nullptr;
56         napi_get_reference_value(env, observer->callback_, &callback);
57         return callback;
58         }, genArgs);
59 }
60 } // namespace OHOS::DistributedData
61