Skip to content

Instantly share code, notes, and snippets.

@igoticecream
Created January 31, 2017 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igoticecream/47b0946996fe9a88407dd564600fe3be to your computer and use it in GitHub Desktop.
Save igoticecream/47b0946996fe9a88407dd564600fe3be to your computer and use it in GitHub Desktop.
Event bus implementation with RxJava 2
import com.jakewharton.rxrelay2.PublishRelay;
import com.jakewharton.rxrelay2.Relay;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
@SuppressWarnings({"unused", "FieldCanBeLocal", "WeakerAccess"})
public final class RxBus {
private static volatile RxBus ourInstance = null;
public static RxBus getInstance() {
if (ourInstance == null) {
synchronized (RxBus.class) {
if (ourInstance == null) {
ourInstance = new RxBus();
}
}
}
return ourInstance;
}
private final Relay<Object> relay;
private RxBus() {
relay = PublishRelay.create().toSerialized();
}
public void post(Object event) {
relay.accept(event);
}
public <T> Disposable receive(final Class<T> clazz, Consumer<T> consumer) {
return receive(clazz).subscribe(consumer);
}
public <T> Observable<T> receive(final Class<T> clazz) {
return receive().ofType(clazz);
}
public Observable<Object> receive() {
return relay;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment