Files
react-native/ReactCommon/react/bridging/LongLivedObject.cpp
T
Scott Kyle 30cb78e709 New bridging API for JSI <-> C++
Summary:
This adds  `bridging::toJs` and `bridging::fromJs` functions that will safely cast to and from JSI values and C++ types. This is extensible by specializing `Bridging<T>` with `toJs` and/or `fromJs` static methods. There are specializations for most common C++ and JSI types along with tests for those.

C++ functions and lambdas will effortlessly bridge into JS, and bridging JS functions back into C++ require you to choose `SyncCallback<R(Args...)>` or `AsyncCallback<Args...>` types. The sync version allows for having a return value and is strictly not movable to prevent accidentally moving onto another thread. The async version will move its args onto the JS thread and safely call the callback there, but hence always has a `void` return value.

For promises, you can construct a `AsyncPromise<T>` that has `resolve` and `reject` methods that can be called from any thread, and will bridge into JS as a regular `Promise`.

Changelog:
[General][Added] - New bridging API for JSI <-> C++

Reviewed By: christophpurrer

Differential Revision: D34607143

fbshipit-source-id: d832ac24cf84b4c1672a7b544d82e324d5fca3ef
2022-03-11 12:47:51 -08:00

59 lines
1.4 KiB
C++

/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "LongLivedObject.h"
namespace facebook {
namespace react {
// LongLivedObjectCollection
LongLivedObjectCollection &LongLivedObjectCollection::get() {
static LongLivedObjectCollection instance;
return instance;
}
LongLivedObjectCollection::LongLivedObjectCollection() {}
void LongLivedObjectCollection::add(std::shared_ptr<LongLivedObject> so) const {
std::lock_guard<std::mutex> lock(collectionMutex_);
collection_.insert(so);
}
void LongLivedObjectCollection::remove(const LongLivedObject *o) const {
std::lock_guard<std::mutex> lock(collectionMutex_);
auto p = collection_.begin();
for (; p != collection_.end(); p++) {
if (p->get() == o) {
break;
}
}
if (p != collection_.end()) {
collection_.erase(p);
}
}
void LongLivedObjectCollection::clear() const {
std::lock_guard<std::mutex> lock(collectionMutex_);
collection_.clear();
}
size_t LongLivedObjectCollection::size() const {
std::lock_guard<std::mutex> lock(collectionMutex_);
return collection_.size();
}
// LongLivedObject
LongLivedObject::LongLivedObject() {}
LongLivedObject::~LongLivedObject() {}
void LongLivedObject::allowRelease() {
LongLivedObjectCollection::get().remove(this);
}
} // namespace react
} // namespace facebook