mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
Lazily instantiate native modules
Summary: Instead of sending a list of modules over to JS on startup (and actually blocking script execution) instead provide a proxy object that constructs each of these lazily. Reviewed By: lexs Differential Revision: D3936979 fbshipit-source-id: 71bde822f01eb17a29f56c5e60e95e98e207d74d
This commit is contained in:
committed by
Facebook Github Bot
parent
606fc11487
commit
9ed9bca0bf
@@ -0,0 +1,63 @@
|
||||
// Copyright 2004-present Facebook. All Rights Reserved.
|
||||
|
||||
#include "JSCNativeModules.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace facebook {
|
||||
namespace react {
|
||||
|
||||
JSCNativeModules::JSCNativeModules(std::shared_ptr<ModuleRegistry> moduleRegistry) :
|
||||
m_moduleRegistry(std::move(moduleRegistry)) {}
|
||||
|
||||
JSValueRef JSCNativeModules::getModule(JSContextRef context, JSStringRef jsName) {
|
||||
std::string moduleName = String::ref(jsName).str();
|
||||
|
||||
const auto it = m_objects.find(moduleName);
|
||||
if (it != m_objects.end()) {
|
||||
return static_cast<JSObjectRef>(it->second);
|
||||
}
|
||||
|
||||
auto module = createModule(moduleName, context);
|
||||
if (!module.hasValue()) {
|
||||
return JSValueMakeUndefined(context);
|
||||
}
|
||||
|
||||
// Protect since we'll be holding on to this value, even though JS may not
|
||||
module->makeProtected();
|
||||
|
||||
auto result = m_objects.emplace(std::move(moduleName), std::move(*module)).first;
|
||||
return static_cast<JSObjectRef>(result->second);
|
||||
}
|
||||
|
||||
void JSCNativeModules::reset() {
|
||||
m_genNativeModuleJS = nullptr;
|
||||
m_objects.clear();
|
||||
}
|
||||
|
||||
folly::Optional<Object> JSCNativeModules::createModule(const std::string& name, JSContextRef context) {
|
||||
if (!m_genNativeModuleJS) {
|
||||
auto global = Object::getGlobalObject(context);
|
||||
m_genNativeModuleJS = global.getProperty("__fbGenNativeModule").asObject();
|
||||
m_genNativeModuleJS->makeProtected();
|
||||
|
||||
// Initialize the module name list, otherwise getModuleConfig won't work
|
||||
// TODO (pieterdb): fix this in ModuleRegistry
|
||||
m_moduleRegistry->moduleNames();
|
||||
}
|
||||
|
||||
auto result = m_moduleRegistry->getConfig(name);
|
||||
if (!result.hasValue()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Value moduleInfo = m_genNativeModuleJS->callAsFunction({
|
||||
Value::fromDynamic(context, result->config),
|
||||
JSValueMakeNumber(context, result->index)
|
||||
});
|
||||
CHECK(!moduleInfo.isNull()) << "Module returned from genNativeModule is null";
|
||||
|
||||
return moduleInfo.asObject().getProperty("module").asObject();
|
||||
}
|
||||
|
||||
} }
|
||||
Reference in New Issue
Block a user