MQTT: Android EventBus
I think to share some facts with you which I collected from my current android project.I have to handle lots of API callings while developing that app.So when we come to networking part of our Android app we can not neglect Retrofit because that has a capability to handle API callings smoothly without affecting UI thread.But today I’m not going to talk about Retrofit instead of that worth to discuss Relation between EventBus with Retrofit.
Actually, what is the EventBus?
EventBus is an open-source library for Android using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code — simplifying the code, removing dependencies, and speeding up app development.When we set one event as publisher and subscribe some classes or fragment for that event.So when the publisher is posting something EventBus automatically invoke subscribers.
There is 3 steps in EventBus
1. Define events
public static class MessageEvent { /* Additional fields if needed */ }
2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode
@Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); }
3. Post events
EventBus.getDefault().post(new MessageEvent());
Here I added basically how to added EventBus to your project.Now we can discuss how to effective when both Retrofit and EventBus come to play together. When it’s come to API call handling we can use two OnEvent methods to complete the related action.one OnEvent method uses to send the Request parameters to Retrofit Request method and other OnEvent method use to get API response to the related activity of fragment. So need to worry about threads and other stuffs whenever the API call finish EventBus fire the related activities of fragments using OnEvent function. Bellow I added a example which I selected from this blog.So you can get far better idea about what was discussed above paragraph.