Skip to content

Instantly share code, notes, and snippets.

@brendanw
Created August 17, 2016 06:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brendanw/74e8af23e13ff00203af5fed2b571971 to your computer and use it in GitHub Desktop.
Save brendanw/74e8af23e13ff00203af5fed2b571971 to your computer and use it in GitHub Desktop.
RxBus with Sticky Events
/**
* An RxJava-backed EventBus class that can support sending and receiving multiple event types.
*
* Based on https://gist.github.com/benjchristensen/04eef9ca0851f3a5d7bf
*/
public class EventBus<T> {
private static EventBus<Object> INSTANCE;
private List<T> events;
private Subject<T, T> publishSubject =
new SerializedSubject<>(PublishSubject.<T>create());
public static EventBus getInstance() {
if (INSTANCE == null) {
INSTANCE = new EventBus<>();
}
return INSTANCE;
}
public EventBus() {
events = new ArrayList<>();
}
/**
* Sends an event that will only be consumed by real-time subscribers
* @param update
* @param <E>
*/
public <E extends T> void send(E update) {
publishSubject.onNext(update);
}
/**
* Sends an event that will be stored until consumed. For example, if a class
* subscribes to this event long after it is fired, it can still consume this event
* by calling asObservable().
* @param update
* @param <E>
*/
public <E extends T> void sendSticky(E update) {
events.add(update);
publishSubject.onNext(update);
}
public <E extends T> void removeSticky(E update) {
events.remove(update);
}
public <E extends T> Observable<E> asObservable(Class<E> eventClass) {
return Observable.merge(asHotObservable(eventClass), asColdObservable(eventClass));
}
private <E extends T> Observable<E> asHotObservable(Class<E> eventClass) {
return publishSubject.ofType(eventClass);
}
private <E extends T> Observable<E> asColdObservable(Class<E> eventClass) {
return Observable.from(new ArrayList<>(events))
.ofType(eventClass);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment