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