Skip to content

Instantly share code, notes, and snippets.

@nicolasjafelle
Last active May 28, 2018 23:16
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicolasjafelle/f779ffa131f642579f9481a8eb9a72a1 to your computer and use it in GitHub Desktop.
Save nicolasjafelle/f779ffa131f642579f9481a8eb9a72a1 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