React Native模块-存储Java类的最佳实践

问题描述

我正在用Kotlin构建一个React Native模块。我有一个外部Java SDK,可以发现多种协议/网络/服务器上的外围设备。

一个类似的发现类:

class discovery(params: Params) {

  fun start() {
    // ...
  }

  fun stop() {
    // ...
  }

}

我想将 startdiscovery() stopdiscovery()函数传递给React Bridge。

客户端可以同时在多个协议/服务器/ ...上搜索manny设备。因此,这将需要同时实例化许多 discovery 类,并在必要时停止其中的一些。某种发现池。

因此,我想将对实例化对象的引用传递给Javascript,这样它每次想调用一个方法时都可以给我回馈。但是React Bridges不允许将Java对象传递给JavaScript。有什么好的方法吗?

解决方法

只需尝试在Java中进行异步操作,以使线程不会卡住并且不会丢失性能(如果您有异步操作,请返回诺言)。

public class DummyModule extends ReactContextBaseJavaModule {
MyDummyClass dummy // this context

public DummyModule(final ReactApplicationContext reactContext){
super(reactContext);
}

@Override
    // getName is required to define the name of the module represented in
    // JavaScript
    public String getName() {
        return "DummyModule";
    }
@ReactMethod
    public void startMyClass() {
       this.dummy = new MyDummyClass();
    }

@ReactMethod
    public void fooActionClass() {
       if(this.dummy != null){
           this.dummy.fooAction();
       }
    }
}

在您的JavaScript代码中

import { NativeModules } from 'react-native';
const dummyModule = NativeModules.DummyModule;

dummyModule.startMyClass();
// Make sure that u call the action when the class is instanciated.
dummyModule.fooActionClass();