Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Event Bus implementation with RxJava. It also post all event in the UI Thread.
import android.os.Handler;
import android.os.Looper;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.internal.util.SubscriptionList;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
* Created by nicolas on 7/21/16.
public class RxEventBus {
private static RxEventBus instance;
private final Subject<Object, Object> eventBus = new SerializedSubject<>(PublishSubject.create());
private SubscriptionList subscriptionList;
private final Handler mainThread = new Handler(Looper.getMainLooper());
private RxEventBus() {
subscriptionList = new SubscriptionList();
public static RxEventBus getInstance() {
if(instance == null) {
instance = new RxEventBus();
return instance;
public void post(final Object event) {
if(Looper.myLooper() == Looper.getMainLooper()) {
}else { Runnable() {
public void run() {
public <T> Subscription register(final Class<T> eventClass, final Action1<T> onNext) {
Subscription subs = eventBus.filter(new Func1<Object, Boolean>() {
public Boolean call(Object event) {
return event.getClass().equals(eventClass);
}).map(new Func1<Object, T>() {
public T call(Object object) {
return (T) object;
return subs;
public void unregister(Subscription subscription) {
public void unregisterAll() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment