Created
January 31, 2017 18:49
-
-
Save igoticecream/47b0946996fe9a88407dd564600fe3be to your computer and use it in GitHub Desktop.
Event bus implementation with RxJava 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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