react-native icon indicating copy to clipboard operation
react-native copied to clipboard

ReadableMap getCallback (Android)

Open mickeyinfoshan opened this issue 11 years ago • 4 comments

Any way to get a method of the object passed to native module

mickeyinfoshan avatar Nov 17 '15 08:11 mickeyinfoshan

NativeModules can take a callback or a promise as an argument.

    @ReactMethod
    public void doSomething(final ReadableMap options, final Callback callback) {
        // do stuff
        callback.invoke(result);
    }

or

    @ReactMethod
    public void doSomething(final ReadableMap options, final Promise promise) {
        try {
            // do stuff

            promise.resolve(result);
        } catch (Exception e) {
            promise.reject(e.getMessage());
        }
    }

satya164 avatar Nov 17 '15 10:11 satya164

@satya164 I know. But if there're multiple callbacks, it's hard to keep the code tidy. Besides, keeping the arguments in the right order is no easy job. It's common in javascript that wrap the arguments as an object to keep the code clean.

mickeyinfoshan avatar Nov 17 '15 11:11 mickeyinfoshan

You can write a wrapper on javascript side which passes multiple callbacks to the module, but exposes a simpler API to your app.

like,

MyModule.doStuff = opts => MyNativeModule.doStuff(opts.success, opts.error);

MyModule.doStuff({ success: fn, error: fn });

satya164 avatar Nov 17 '15 11:11 satya164

That's the solution I just worked out! THX!!

mickeyinfoshan avatar Nov 17 '15 12:11 mickeyinfoshan