David Jones
David Jones

Reputation: 10219

How to run React Native module methods on the main thread on Android

On iOS, we can ensure that the methods in a custom React Native module are executed on the main thread using a few lines of code:

- (dispatch_queue_t)methodQueue {
  return dispatch_get_main_queue();
}

What would be the correct way to do this on Android?

Upvotes: 3

Views: 4917

Answers (2)

unify
unify

Reputation: 6351

Use the following provided util

import com.facebook.react.bridge.UiThreadUtil

UiThreadUtil.runOnUiThread { 
// your code here
}

Upvotes: 2

Follow de official docs

"Native modules should not have any assumptions about what thread they are being called on, as the current assignment is subject to change in the future. If a blocking call is required, the heavy work should be dispatched to an internally managed worker thread, and any callbacks distributed from there".

If you want to run code from mainThread you should use Handler class from android.

Handler handler = new Handler(context.getMainLooper()); 
handler.post(new Runnable(){ // Code that needs to be run on the main thread. })

Running code in main thread from another thread

Upvotes: 4

Related Questions