MQTT: Android EventBus

From OnnoWiki
Revision as of 05:50, 12 April 2022 by Onnowpurbo (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.


The EventBus API is as easy as 1-2-3

Before we get started make sure to add EventBus as a dependency to your project.

Step 1: Define events

Events are POJO (plain old Java object) without any specific requirements.

public class MessageEvent {
 
    public final String message;
 
    public MessageEvent(String message) {
        this.message = message;
    }
}

Step 2: Prepare subscribers

Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the @Subscribe annotation. Note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).

// This method will be called when a MessageEvent is posted (in the UI thread for Toast)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}

// This method will be called when a SomeOtherEvent is posted
@Subscribe
public void handleSomethingElse(SomeOtherEvent event) {
    doSomethingWith(event);
}

Subscribers also need to register themselves to and unregister from the bus. Only while subscribers are registered, they will receive events. In Android, in activities and fragments you should usually register according to their life cycle. For most cases onStart/onStop works fine:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

Step 3: Post events

Post an event from any part of your code. All currently registered subscribers matching the event type will receive it.

EventBus.getDefault().post(new MessageEvent("Hello everyone!"));


Referensi