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

2

7

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?

Ethylethylate answered 14/2, 2016 at 3:9 Comment(0)
E
18

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.

Ethylethylate answered 14/2, 2016 at 3:33 Comment(1)
Yes. The have completely moved to annotations and the method name doesn't matter anymore. Glad you found the answer.Pontefract
M
6

@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.

Modulation answered 26/2, 2016 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.