Skip to content

Instantly share code, notes, and snippets.

@marwinxxii
Created November 23, 2015 18:32
Show Gist options
  • Save marwinxxii/16eb1906daf56f7dd4fa to your computer and use it in GitHub Desktop.
Save marwinxxii/16eb1906daf56f7dd4fa to your computer and use it in GitHub Desktop.
RxJava generic event bus sample
package com.github.marwinxxii.rxsamples;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
public class SeparateBusSample {
public static void test() {
EventBus<String> stringEventBus = new EventBus<>();
EventBus<Long> longEventBus = new EventBus<>();
}
public static class EventBus<T> {
private final Subject<T, T> subject;
public EventBus() {
this(PublishSubject.<T>create());
}
public EventBus(Subject<T, T> subject) {
this.subject = subject;
}
public <E extends T> void post(E event) {
subject.onNext(event);
}
public Observable<T> observe() {
return subject;
}
}
}
package com.github.marwinxxii.rxsamples;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
public class SingleBusSample {
public static void test() {
EventBus<Object> eventBus = new EventBus<>();
Observable<String> stringEventsObservable = eventBus.observeEvents(String.class);
Observable<Long> longEventsObservable = eventBus.observeEvents(Long.class);
}
//class can be non generic and always use Subject<Object, Object>
public static class EventBus<T> {
private final Subject<T, T> subject;
public EventBus() {
this(PublishSubject.<T>create());
}
public EventBus(Subject<T, T> subject) {
this.subject = subject;
}
public <E extends T> void post(E event) {
subject.onNext(event);
}
public Observable<T> observeAllEvents() {
return subject;
}
public <E extends T> Observable<E> observeEvents(Class<E> eventClass) {
return subject.ofType(eventClass);//pass only events of specified type, filter all other
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment