Skip to content

Instantly share code, notes, and snippets.

@vudunguit
Forked from nicolasjafelle/RxEventBus.java
Created September 9, 2016 07:29
Show Gist options
  • Save vudunguit/576744171032bdb4ea02106f40af78b8 to your computer and use it in GitHub Desktop.
Save vudunguit/576744171032bdb4ea02106f40af78b8 to your computer and use it in GitHub Desktop.
Event Bus implementation with RxJava. It also post all event in the UI Thread.
import android.os.Handler;
import android.os.Looper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
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.
*/
//@Singleton
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());
//@Inject
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()) {
eventBus.onNext(event);
}else {
mainThread.post(new Runnable() {
@Override
public void run() {
eventBus.onNext(event);
}
});
}
}
public <T> Subscription register(final Class<T> eventClass, final Action1<T> onNext) {
Subscription subs = eventBus.filter(new Func1<Object, Boolean>() {
@Override
public Boolean call(Object event) {
return event.getClass().equals(eventClass);
}
}).map(new Func1<Object, T>() {
@Override
public T call(Object object) {
return (T) object;
}
}).subscribe(onNext);
subscriptionList.add(subs);
return subs;
}
public void unregister(Subscription subscription) {
subscriptionList.remove(subscription);
}
public void unregisterAll() {
subscriptionList.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment