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

I am a bit confused about using onEvent , onEventMainThread , onEventBackgroundThread and onEventAsync in Greenrobot EventBus 3.0

From what I see in the documentation :

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

But in case the event is sent from the background thread:

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

has 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 stream is the same as the wiring stream (the background stream in my tests).

Starting with version 3.0, the @Subscribe annotation is @Subscribe , so I don’t understand in which case I should use methods other than onEvent . Have they been saved to upgrade from EventBus 2 to 3?

+7
java android event-bus greenrobot-eventbus
source share
2 answers

I found the answer, unlike EventBus 2, the method name is not important, since in EventBus 3 annotations are used in favor of Reflection, so the following actions will work:

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

I keep this question here to save time for those who may have the same question.

+15
source share

@Subscribe is an annotation that registers a method with EventBus, in the past it was done with reflection, so you had to name the methods in a certain way ( onEvent , onEventMainThread , etc.) This had two drawbacks:

  • Reflection in Java is rather slow, and
  • The naming convention is not immediately intuitive for new users.

Both flaws were fixed with the update, so now you can call your methods any way you like and indicate in which thread you want the event to be executed inside the annotation parameters.

+6
source share

All Articles