Event Bus Implementation using Rxjava2 in Android

rxjava and rxandroid are libraries for managing the threading and background tasks in Android applications. They can also be used to implement the Event Bus mechanism. It is so good that even the dedicated Event Bus library otto is deprecated in favor of rxjava and rxandroid. This post will go through the steps of implementing event bus using rxjava 2 in Android.

1. Import rxjava and rxandroid in your gradle file.

compile 'io.reactivex.rxjava2:rxjava:2.0.2'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

2. Create a simple java class called RxEventBus.java

public class RxEventBus {
    public RxEventBus() {
    }

    private PublishSubject<Object> bus = PublishSubject.create();

    public void send(Object o) {
        bus.onNext(o);
    }

    public Observable<Object> toObserverable() {
        return bus;
    }

    public boolean hasObservers() {
        return bus.hasObservers();
    }
}

3. Create java class called Events.java, this will be used as message object to put and get information from the event bus.

public class Events {
    private Events(){}

    public static class Message {
        private String message;
        public Message(String message) {
            this.message = DateFormat.format("MM/dd/yy h:mm:ss aa", System.currentTimeMillis()) + ": " + message;
        }
        public String getMessage() {
            return message;
        }
    }
}

4. With the above, we already set up an Event Bus for us to use. From here on, let’s go through how to use it. Go ahead and create a MyApp.java that extends the Application class.

public class MyApp extends Application {
    private RxEventBus bus;

    @Override
    public void onCreate() {
        bus = new RxEventBus();
        Log.d("before", "" + System.currentTimeMillis());
        new Thread() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                bus.send(new Events.Message("Hey I just took a nap, how are you!"));
            }
        }.start();
        Log.d("after ", "" + System.currentTimeMillis());
    }

    public RxEventBus bus() {
        return bus;
    }
}

5. Receiving messages in the MainActivity.java, the message is received after this line of code bus.send(new Events.Message("Hey I just took a nap, how are you!")); in the onCreate of the MyApp

public class MainActivity extends AppCompatActivity {

    TextView tvDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        tvDisplay = (TextView) findViewById(R.id.tv_display);


        ((MyApp)getApplication()).bus().toObserverable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object) throws Exception {
                        String msg = ((Events.Message) object).getMessage();
                        tvDisplay.setText(msg + "\n\n" + tvDisplay.getText().toString());
                    }
                });


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((MyApp)getApplication()).bus().send(new Events.Message("You clicked the email button!"));
            }
        });
    }

}

The following are not related to rxjava, they are here just for your convenience

6. Make sure you add this MyApp to the name attribute of the application tag in the manifest file.

android:name=".MyApp"

7. The content_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.rxeventbus.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/tv_display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

Search within Codexpedia

Custom Search

Search the entire web

Custom Search