React native call native: callback (Android)

Time:2021-6-25

In react native, it can be customized in Java layerReactMethod(https://segmentfault.com/a/1190000004486024)This way, native method in Android can be called directly in JavaScript layer
But in most method calls, we need to know what the result is after calling the method and whether there are exceptions. JavaScript itself is an event driven language. Callback method can be used in JavaScript to process the result returned by function. Similarly, in react native, theCallbackandPromiseInterface to handle the callback of JavaScript calling Java methods.

Callback

CallbackIs an interface in react. Bridge, which acts asReactMethodIs used to map the callback function of JavaScript.CallbackThe interface defines only one methodinvoke, invoke accepts multiple parameters, which must be supported in react.bridge.
First, we define a class to call JavaScript

public class StoreModule extends ReactContextBaseJavaModule {

    @Override
    public String getName() {
        return "StoreModule";
    }

}

Specify its name asStoreModule
Now we have a way to save ituserNameandpasswordreachShardPreferencesIn this method, we need to define twoCallbackParameter, one is used to deal with the success of the case, one is used to deal with the exception of the case.


    @ReactMethod
    public void addUser(String userName, String password, Callback successCallback, Callback errorCallback) {
        try {
            if (TextUtils.isEmpty(userName)) {
                errorCallback.invoke("user name is empty");
                return;
            }
            if (TextUtils.isEmpty(password)) {
                errorCallback.invoke("password is empty");
                return;
            }
            preferences.edit().putString(USER_NAME, userName).commit();
            preferences.edit().putString(PASSWORD, password).commit();
            successCallback.invoke("add user success");
        } catch (Exception e) {
            e.printStackTrace();
            errorCallback.invoke(e.getMessage());
        }
    }

Now we have one withCallbackAs a parameterStoreModuleClass, add an instance of this classReactPackageOfcreateNativeModulesThis method can be called in the JavaScript layer.
In JavaScript, call theCallbackMethod of parameter selection:

var {NativeModules}=require('react-native');
var storeModule=NativeModules.StoreModule;
storeModule.addUser("jjz","123456",(msg)=>{
    alert(msg);
  },(errorMsg)=>{
    alert(errorMsg)
});

The method callback methods here are anonymous functions that we use. After JavaScript calls Java, the processing result will be changed toCallbackReturn to JavaScript in the form of, and then process the corresponding results in JavaScript.

Promise

Promise isES6More friendly API for asynchronous programming and callback added in(https://segmentfault.com/a/1190000004505028),With promise, you can handle callbacks more concisely and flexibly.
stayreact.briageDefined inPromiseThe interface is implementedresolveandrejectHow to do it,resolveIt is used to process the result correctly,rejectUsed to handle abnormal situations.
stayStoreModuleDefine a supportPromiseMethod as parameter:


    @ReactMethod
    public void login(String userName, String password, Promise promise) {
        String storeUserName = preferences.getString(USER_NAME, "");
        String storePassword = preferences.getString(PASSWORD, "");
        if (!equalsString(userName, storeUserName)) {
            promise.reject("0", "user name is wrong");
            return;

        }
        if (!equalsString(password, storePassword)) {
            promise.reject("1", "password is wrong");
            return;

        }
        WritableMap map = Arguments.createMap();
        map.putDouble("user_id", 1);
        promise.resolve(map);

    }

thereWritableMapInheritedReadableMapDefines the parameter conversion in Java and JavaScript
When calling this method, a promise object will be returned in JavaScript, which means that you can use JavaScript directly.
Call in JavaScript:

storeModule.login('jjz','123456').then((map)=>{
    alert(map['user_id']);
  },(code,message)=>{
    alert(message);
})

Using promise is better than usingCallbackMore concise, but also more flexible switching between threads.

Code address:https://github.com/jjz/react-native/tree/master/RNJava

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]