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?

2

There are 2 answers

1
grim On BEST ANSWER

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.

0
shredder On

@Subscribe is the annotation that registers the method with the EventBus, in the past this was done with reflection, that's why you had to name the methods in a particular way (onEvent, onEventMainThread etc). This had two drawbacks:

  1. Reflection is quite slow in Java, and
  2. The naming convention is not immediately intuitive to new users.

Both drawbacks have been eliminated with the update, so now you can name your methods whatever you like and indicate in which thread you would like the event to run inside the annotations parameters.