Skip to content

Instantly share code, notes, and snippets.

@Jween
Created November 22, 2018 03:24
Show Gist options
  • Save Jween/592b99ae8b56162fd93f4756f3facf0e to your computer and use it in GitHub Desktop.
Save Jween/592b99ae8b56162fd93f4756f3facf0e to your computer and use it in GitHub Desktop.
package io.jween.rx;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;
/**
* RxJava version Event Bus
*
* To post an event:
* <pre>{@code
* Object event = new SomeEventClass(param1, param2);
* Bus.get().post(event);
* }</pre>
*
* To observe an event:
* <pre>{@code
* Bus.get().on(SomeEventClass.class)
* .subscribe(new Consumer<SomeEventClass>() {
* @Override
* public void call(SomeEventClass runnable) {
* // do your stuff
* }
* });
* }</pre>
*
* Created by Jwn on 2017/1/17.
*/
public class Bus {
private static final Bus INSTANCE = new Bus();
private final PublishSubject<Object> busSubject = PublishSubject.create();
public static Bus get() {
return INSTANCE;
}
public void post(Object event) {
busSubject.onNext(event);
}
public <T> Observable<T> on(Class<T> eventClass) {
return busSubject.ofType(eventClass);
}
public <T> Observable<T> onMainThread(Class<T> eventClass) {
return on(eventClass)
.observeOn(AndroidSchedulers.mainThread());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment