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?
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.
@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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With