Search code examples
javaandroidevent-busgreenrobot-eventbusgreenrobot-eventbus-3.0

Greenbot Eventbus 3.0: What is the difference between onEvent, onEventMainThread, onEventBackgroundThread and onEventAsync?


I am a bit confused with the usage of onEvent, onEventMainThread, onEventBackgroundThread and onEventAsync in Greenrobot's EventBus 3.0

From what I see in the documentation:

  • onEvent is used with ThreadMode.POSTING (default)
  • onEventMainThread is used with ThreadMode.MAIN
  • onEventBackgroundThread is used with ThreadMode.BackgroundThread
  • onEventAsync is used with ThreadMode.ASYNC

But in the case where the event is posted from a background thread:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(MyEvent event) {
    // some UI manipulation
}

Has exactly the same behavior as:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MyEvent event) {
    // some UI manipulation
}

And:

@Subscribe
public void onEventMainThread(MyEvent event) {
    // some UI manipulation
}

Throws CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. because the thread is the same as the posting thread (background thread in my tests).

Since version 3.0, the @Subscribe annotation is required so I don't understand in which case I should use the methods other than onEvent. Were they kept to facilitate upgrade from EventBus 2 to 3?


Solution

  • I've found the answer, as opposed to EventBus 2, the method name is not important since on EventBus 3 annotations are used in favor of Reflection, so the following will work:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void someMethodName(MyEvent event) {
        // some UI manipulation
    }
    

    I'm keeping this question here to spare the time for someone who might have the same question.