Reputation: 57
I am trying to create a TurboModule
for my app. I don't want to create it as a separate module as mentioned over here. I want it to be part of my app So I created a RTNCalculator
folder inside that a js
folder and created NativeCalculator.ts
file. Then in the package.json of my application I added the following code
"codegenConfig": {
"libraries": [
{
"name": "NativeCalculator",
"type": "modules",
"jsSrcsDir": "./RTNCalculator/js"
}
]
}
My NativeCalculator.ts
code
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import {TurboModuleRegistry} from 'react-native';
export interface Spec extends TurboModule {
add(a: number, b: number): Promise<number>;
pickImage(): Promise<void>;
someDummyMethod(): Promise<void>;
addTwo(a: number, b: number): Promise<number>;
}
export default TurboModuleRegistry.get<Spec>('RTNCalculator') as Spec | null;
Then I ran ./gradlew generateCodegenArtifactsFromSchema
and in the main android
folder I created the following files
CalculatorModule.kt
and CalculatorPackage.kt
class CalculatorPackage : TurboReactPackage() {
override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
return if (name == CalculatorModule.NAME) {
CalculatorModule(reactContext)
} else {
null
}
}
override fun getReactModuleInfoProvider(): ReactModuleInfoProvider? {
return ReactModuleInfoProvider {
val moduleInfos: MutableMap<String, ReactModuleInfo> = HashMap()
moduleInfos[CalculatorModule.NAME] = ReactModuleInfo(
CalculatorModule.NAME,
CalculatorModule.NAME,
false, // canOverrideExistingModule
false, // needsEagerInit
true, // hasConstants
false, // isCxxModule
true // isTurboModule
)
moduleInfos
}
}
}
class CalculatorModule(context: ReactApplicationContext): NativeCalculatorSpec(context) {
override fun getName(): String {
return NAME
}
override fun add(a: Double, b: Double, promise: Promise?) {
promise!!.resolve(a+b)
}
override fun pickImage(promise: Promise?) {
}
override fun someDummyMethod(promise: Promise?) {
}
override fun addTwo(a: Double, b: Double, promise: Promise?) {
}
companion object {
const val NAME = "RTNCalculator"
}
}
Then in MainApplication.java I added packages.add(new CalculatorPackage());
Then to use it in my App.tsx
import RTNCalculator from './RTNCalculator/js/NativeCalculator';
Now when I call the add method of RTNCalculator
I get undefined. What am I missing?
I have enabled the new architecture for my app
Full source code https://github.com/BraveEvidence/TMTry
Upvotes: 4
Views: 1054