在iOS上,我们可以使用几行代码确保自定义React Native模块中的方法在主线程上执行:
- (dispatch_queue_t)methodQueue {
return dispatch_get_main_queue();
}
在Android上正确的方法是什么?
在iOS上,我们可以使用几行代码确保自定义React Native模块中的方法在主线程上执行:
- (dispatch_queue_t)methodQueue {
return dispatch_get_main_queue();
}
在Android上正确的方法是什么?
遵循官方文档。
“本地模块不应对其被调用的线程做出任何假设,因为当前分配可能会在未来更改。如果需要阻塞调用,则应将繁重的工作调度到内部管理的工作线程,并从那里分发任何回调。”
如果您想从主线程运行代码,则应使用android中的Handler类。
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable(){ // Code that needs to be run on the main thread. })
import com.facebook.react.bridge.UiThreadUtil
UiThreadUtil.runOnUiThread {
// your code here
}