How to write a simple native-native native module with callback

How to get this working, in the easiest way, I have problems sending a callback to respond, maybe I missed something.

@ReactMethod
public void testCallback(Callback cb) {

String sampleText = "Java is fun";
int textLength = sampleText.length();
    try{
        cb.invoke(textLength);
    }catch (Exception e){
        cb.invoke("err");
    }
}

On the reaction side

var getNativeCallback = require('react-native-native-callback');


getNativeCallback.testCallback(function (result){
    console.log(result)
})
+4
source share
1 answer

I have to face the same problem, and finally, I have to use a different approach, since there seems to be no callback type for @ReactProp.

Instead, I used the Events method to have Android native feedback for React Native.

On the Android side, I configured the SendEvent function, which was run as needed:

private void sendEventToReactFromAndroid(ReactContext reactContext,String eventName, @Nullable WritableMap params) {
    reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}

@Override
public void customAndroidListenerFunction() {
    sendEvent(mcontext, "EventName", null);

}

React , :

var {DeviceEventEmitter} = require('react-native');
...
componentWillMount: function() {
    DeviceEventEmitter.addListener('EventName', function(e: Event) {
        console.log("Received event loud and clear in the React Native side!");
    });
},
...

, .

+1

Source: https://habr.com/ru/post/1613067/


All Articles