Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
David Jones Avatar asked Nov 25 '25 09:11

David Jones


1 Answers

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

like image 199
anthony willis muñoz Avatar answered Nov 28 '25 00:11

anthony willis muñoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!