ReactNative系列之二十六JS代码同步调用JAVA方法

在安卓平台上,通常我们使用继承“ReactContextBaseJavaModule.java”,并通过注解方式“@ReactMethod”,添加至packages。然后注册到至JS-C++-Java的通信消息队列中。

大部分情况下,由于RN的页面渲染和通信机制,RN推荐我们使用异步进行通信。

然,如果我们固执的想用同步方式。这里给出解决办法:

1.原生的方法中增加括号内的注解部分
@ReactMethod(isBlockingSynchronousMethod = true)
public int getTestSyncCount(int a, int b) {
    return a + b;
}

2.js调用部分

console.log("yeputi_wk", "RnAsstesModules : " + RnAssetsModule.getTestSyncCount(11, 11));

注1:这种方式用起来还是比较方便的,但一定要注意不要卡线程!!!查询RN的源码我们发现在UIManagerModule.java中也使用了同步方法。方法如下:

@DoNotStrip
@ReactMethod(isBlockingSynchronousMethod = true)
public @Nullable WritableMap getConstantsForViewManager(final String viewManagerName) {
...  // 此处源码省略,此类为JS调用原生View的非常重要的管理类,此方法为原生View的属性行为(如ScrollView的onScroll属性)都将注册到viewMaangerContants这个map中,然后同步于JS中,供JS的View定义调用。
}

注2: ReactNative源码中对同步的解释为:

/**
 * Whether the method can be called from JS synchronously **on the JS thread**,
 * possibly returning a result.
 *
 * WARNING: in the vast majority of cases, you should leave this to false which allows
 * your native module methods to be called asynchronously: calling methods
 * synchronously can have strong performance penalties and introduce threading-related
 * bugs to your native modules.
 *
 * In order to support remote debugging, both the method args and return type must be
 * serializable to JSON: this means that we only support the same args as
 * {@link ReactMethod}, and the hook can only be void or return JSON values (e.g. bool,
 * number, String, {@link WritableMap}, or {@link WritableArray}). Calling these
 * methods when running under the websocket executor is currently not supported.
 */
boolean isBlockingSynchronousMethod() default false;

如果有疑问或不同见解,请留言或关注,专注于ReactNative原创文章~

猜你喜欢

转载自blog.csdn.net/yeputi1015/article/details/81285488
今日推荐