0

EventBus for Android

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. It speeds up app development by simplifying the code and removing dependencies. This journal will show how to implement EventBus into your android project herby demostrating the benefits of using this library to simplify, optimies and clean up your project no matter how huge. Before we proceed, here are some important features of EventBus:

Features of EventBus

  • Convenient Annotation based API: Convenient Annotation based API: Simply put the @Subscribe annotation to your subscriber methods. Because of a build time indexing of annotations, EventBus does not need to do annotation reflection during your app’s run time.
  • Android main thread delivery: When interacting with the UI, EventBus can deliver events in the main thread regardless how an event was posted.
  • Background thread delivery: If your subscriber does long running tasks, EventBus can also use background threads to avoid UI blocking.
  • Event & Subscriber inheritance: In EventBus, the object oriented paradigm apply to event and subscriber classes. Let’s say event class A is the superclass of B. Posted events of type B will also be posted to subscribers interested in A. Similarly the inheritance of subscriber classes are considered.
  • Jump start: You can get started immediately – without the need to configure anything – using a default EventBus instance available from anywhere in your code.

Adding EventBus to your project

  1. Check if you are having the latest library from here http://search.maven.org/#search|ga|1|g%3A"org.greenrobot" AND a%3A"eventbus"
  2. Add to gradle compile 'org.greenrobot:eventbus:3.0.0'

And thats it. Now you have succesfully added the library to your project. Eventbus comes with a lot of practical features some of which will now be covered in this article. As the image below demostrates how the communication occurs.

There are mainly two major entities (The Publisher and the Subscriber). Think of the subscribers as the ones that starts and initiate the events. But before an event can be started we need to create an Event class.

public class NameEvent {
    private String name;

    public NameEvent(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Now whenever the Publisher wants to send and event, it can be archieved by this line of code: EventBus.getDefault().post(new NameEvent()); This will thus send a broadcast to all the Subscibers and pass the data (New name) to the receivers. To add a subscriber to your activity simply add this:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onNameEvent(NameEvent event) {
String new_name = event.getName();
}

As you guessed this will return the new name passed into our event. You should note that ths event can be used to pass any data type or object to any subscribed activity or fragments. Remember to register and unregister your Eventbus when starting or clossing your activity.

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

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

Delivery Threads (ThreadMode) EventBus handles threading, by creating multiple threads evebts can be posted on other threads rather than the posting thread hereby improving the performance of the app. In EventBus, you may define the thread that will call the event handling method by using one of the four ThreadModes. 1. ThreadMode: POSTING Here Subscribers are called in the same thread posting the event. This is the default. Event delivery is done synchronously and all subscribers will have been called once the posting is done. This ThreadMode implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers using this mode should return quickly to avoid blocking the posting thread, which may be the main thread. Example:

@Subscribe(threadMode = ThreadMode.POSTING)  
public void onNameEvent(NameEvent event) {
String new_name = event.getName();
}

2. ThreadMode: MAIN Here Subscribers will be called in Android’s main/UI thread. If the posting thread is the main thread, event handler methods will be called directly (synchronously like described for ThreadMode.POSTING). Event handlers using this mode must return quickly to avoid blocking the main thread. Example of a usecase is having an object on your interface such as an editText or TextView.

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onNameEvent(NameEvent event) {
String new_name = event.getName();
textViewName.setText(new_name);
}

3. ThreadMode: BACKGROUND Here Subscribers are called in a background thread. If posting thread is not the main thread, event handler methods will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single background thread that will deliver all its events sequentially. Event handlers using this mode should try to return quickly to avoid blocking the background thread.

@Subscribe(threadMode = ThreadMode.BACKGROUND)  
public void onNameEvent(NameEvent event) {
String new_name = event.getName();
saveToDatabase(new_name);
}

4. ThreadMode: ASYNC This can be used when you are trying to execute a large task such as downloading a huge chunk of data and might take a while to be completed. his is always independent from the posting thread and the main thread. Posting events never wait for event handler methods using this mode. Event handler methods should use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.

@Subscribe(threadMode = ThreadMode.ASYNC)  
public void onNameEvent(NameEvent event) {
String new_name = event.getName();
downloadUserData(new_name);
}

EventBus also comes along with some pretty cool features such as Sticky Events, ProGuard and much more. For further info please refer to the official website and docs >> http://greenrobot.org/eventbus/documentation/


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí