Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading events using GreenRobot EventBus

I've just started looking at GreenRobot's EventBus for Android and have a question about threading.

I have a long-running process that I'd like to run on a background thread which, when completed, updates the UI.

So something like:

public void onEventBackgroundThread(MyEvent event) {
        doSomeLongRunningProcess();
        updateUI();
    }

Obviously updateUI() can't be called here because it would also run in the background.

So what would be the recommended way to handle this? Fire another event from within my onEventBackgroundThread() which will run on the UI thread? Or fire it from the long-running-process itself? Or is there a better pattern?

like image 863
jFort Avatar asked May 17 '13 07:05

jFort


2 Answers

I would probably fire another event when you get the result.

public void onEventBackgroundThread(MyEvent event) {
    doSomeLongRunningProcess();
    EventBus.getDefault().post(new MyEventResult());
}

Be aware though: reading the docs, you find this:

BackgroundThread: Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single background thread that will deliver all its events sequentially. Event handlers using this mode should try to return quickly to avoid blocking the background thread.

If you take a long time in this method, other EventBus callbacks will be delayed which will probably translate to an unresponsive application.

You probably want to use onEventAsync:

Async: Event handler methods are called in a separate thread. This is always independent from the posting thread and the main thread. Posting events never wait for event handler methods using this mode. Event handler methods should use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.

like image 125
Pedro Loureiro Avatar answered Nov 09 '22 19:11

Pedro Loureiro


I'd suggest firing another event which will be handled by onEventMainThread method.

This has a positive impact of the updateUI not being called at all if the receiver is already unregistered (e.g. activity unregistered because it was destroyed).

like image 33
MaciejGórski Avatar answered Nov 09 '22 19:11

MaciejGórski