React Native module - Best practice to store java class

575 views Asked by At

I'm building a React Native module with Kotlin. I have an external Java SDK that can discover peripherals on multiple protocols / networks / servers.

There is a Discovery class like this :

class Discovery(params: Params) {

  fun start() {
    // ...
  }

  fun stop() {
    // ...
  }

}

I want to pass a startDiscovery() and stopDiscovery() functions to React Bridge.

The client can search for many devices on multiple protocols / servers / ... at the same time. So it would require the instantiation of many Discovery class at the same time and stop some of them if necessary. Some sort of a Pool of discoveries.

So I would like to pass a reference to the instantiated object to Javascript so it can give back to me each time it want to call another method. But React Bridges doesn't allow to pass Java objets to JavaScript. Is there any good pattern to do so ?

1

There are 1 answers

4
anthony willis muñoz On

Just try to make async actions in java so the thread not get stuck and you don't lose performance(return promises if you have async actions).

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();
       }
    }
}

In your javascript code

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();