Skip to content

Instantly share code, notes, and snippets.

@odbol
Last active January 2, 2019 03:22
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 odbol/be84557a737bff799cf9 to your computer and use it in GitHub Desktop.
Save odbol/be84557a737bff799cf9 to your computer and use it in GitHub Desktop.
An event bus for pub/sub to UI related-events. Based on RxJava
dependencies {
// rxjava
api 'io.reactivex.rxjava2:rxjava:2.1.7'
}
package com.odbol.sensorizer.eventbus;
import io.reactivex.Observable;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.ReplaySubject;
import io.reactivex.subjects.Subject;
/***
* An event bus for pub/sub to UI related-events.
*
* Anything that should be shown in the UI should be published here,
* most UIs should subscribe to it and then filter what they want.
*
* Based on http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/
*
* @author tyler
*
*/
public class EventBus<T> {
private final Subject<T> _bus;
protected EventBus(boolean cacheLastValue) {
if (cacheLastValue) {
ReplaySubject<T> pb = ReplaySubject.createWithSize(1);
_bus = pb.toSerialized();
}
else {
PublishSubject<T> pb = PublishSubject.create();
_bus = pb.toSerialized();
}
}
public void send(T event) {
_bus.onNext(event);
}
/***
* Subscribes to events only of the specified type.
*
* @param eventType Type of the events to filter.
*/
public <R extends T> Observable<R> subscribe(final Class<R> eventType) {
return _bus.filter(eventType::isInstance)
.cast(eventType);
}
/***
* Subscribes to all events on this bus.
*/
public Observable<T> subscribe() {
return _bus;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment