• 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 }
28 
GetCallback()29 napi_ref JSObserver::GetCallback()
30 {
31     return callback_;
32 }
33 
ClearCallback()34 void JSObserver::ClearCallback()
35 {
36     if (callback_ == nullptr) {
37         return;
38     }
39     napi_delete_reference(uvQueue_->GetEnv(), callback_);
40     callback_ = nullptr;
41 }
42 
AsyncCall(UvQueue::NapiArgsGenerator genArgs)43 void JSObserver::AsyncCall(UvQueue::NapiArgsGenerator genArgs)
44 {
45     if (callback_ == nullptr) {
46         return;
47     }
48 
49     uvQueue_->AsyncCall(
50         [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         },
59         genArgs);
60 }
61 } // namespace OHOS::DistributedKVStore
62