Android – Threading events using GreenRobot EventBus

androidgreenrobot-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?

Best Solution

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.