Make TurboModules long-lived on Android

Summary: On iOS, calling the `__turboModuleProxy` function with the same name returns the same instance of the TurboModule. Adding this behaviour to Andorid as well.

Reviewed By: mdvacca

Differential Revision: D16553363

fbshipit-source-id: c95e150d6967604a808cfb49877b7a633e33d729
This commit is contained in:
Ramanpreet Nara
2019-08-01 16:31:48 -07:00
committed by Facebook Github Bot
parent a6fffb7cd0
commit e876cc68e7
3 changed files with 22 additions and 3 deletions
@@ -56,20 +56,30 @@ void TurboModuleManager::installJSIBindings() {
}
TurboModuleBinding::install(*runtime_, std::make_shared<TurboModuleBinding>(
[this](const std::string &name) -> std::shared_ptr<TurboModule> {
auto turboModuleLookup = turboModuleCache_.find(name);
if (turboModuleLookup != turboModuleCache_.end()) {
return turboModuleLookup->second;
}
auto cxxModule = turboModuleManagerDelegate_->cthis()->getTurboModule(name, jsCallInvoker_);
if (cxxModule) {
turboModuleCache_.insert({name, cxxModule});
return cxxModule;
}
auto legacyCxxModule = getLegacyCxxJavaModule(name);
if (legacyCxxModule) {
return std::make_shared<react::TurboCxxModule>(legacyCxxModule->cthis()->getModule(), jsCallInvoker_);
auto turboModule = std::make_shared<react::TurboCxxModule>(legacyCxxModule->cthis()->getModule(), jsCallInvoker_);
turboModuleCache_.insert({name, turboModule});
return turboModule;
}
auto moduleInstance = getJavaModule(name);
if (moduleInstance) {
return turboModuleManagerDelegate_->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker_);
auto turboModule = turboModuleManagerDelegate_->cthis()->getTurboModule(name, moduleInstance, jsCallInvoker_);
turboModuleCache_.insert({name, turboModule});
return turboModule;
}
return std::shared_ptr<TurboModule>(nullptr);
@@ -8,6 +8,7 @@
#pragma once
#include <memory>
#include <unordered_map>
#include <fb/fbjni.h>
#include <jsi/jsi.h>
#include <ReactCommon/TurboModule.h>
@@ -37,6 +38,14 @@ private:
std::shared_ptr<JSCallInvoker> jsCallInvoker_;
jni::global_ref<TurboModuleManagerDelegate::javaobject> turboModuleManagerDelegate_;
/**
* TODO(T48018690):
* All modules are currently long-lived.
* We need to come up with a mechanism to allow modules to specify whether
* they want to be long-lived or short-lived.
*/
std::unordered_map<std::string, std::shared_ptr<react::TurboModule>> turboModuleCache_;
jni::global_ref<JTurboModule> getJavaModule(std::string name);
jni::global_ref<CxxModuleWrapper::javaobject> getLegacyCxxJavaModule(std::string name);
void installJSIBindings();