Day016 — EventBus
EventBus is a very good way to communicate between thread. In any decent app, it must have some part of code that runs on thread other than the main thread (UI thread). Handler, intent filter (listening incoming text messages), AsyncTask, and Loader are some of the ways I have tried to accomplish that kind of background task. All of them has their own way to communicate with the main thread, which I found it is confusing and troublesome. EventBus establish a standard pattern for posting data across thread. The way they implement it is straight forward and it can be easily adopted to existing code base.
=================================
I encountered below problem when I am using the v3.0.0 of Eventbus. I was trying to subscribe the event of a successful login and I want to update the UI when an event happened.
@Subscribe
public void onLoginEvent(LoginEvent event) {
}
it has no visible exception on device’s screen. It only displays the exception code when I investigates it under debug mode.
throws below internal error code
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
ThreadMode POSTING is used as default for the subscription. ThreadMode.MAIN should be used for the part of code trying to update the UI. It makes sense as all ui update code must be executed in the main thread.
@Subscribe(threadMode = ThreadMode.MAIN)
public void onLoginEvent(LoginEvent event) {
}
==================================
for v3.0.0, below codes must be added to proguard file to avoid error when minifying the app
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
http://greenrobot.org/eventbus/documentation/proguard/
===================================
honorable mention:
To provide a good user experience all potentially slow running operations in an Android application should run…www.vogella.com
Vogella provides a detail tutorial on background processing. The website constantly updates its content to catch up with new api. very very good. highly recommend it.