5. public class RxEventBus {
private final Subject<Object, Object> subject
= new SerializedSubject<>(PublishSubject.create());
public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.subscribe(handler);
}
public void post(Object event) {
subject.onNext(event);
}
}
RxEventBus.java
6. public class RxEventBusProvider {
private static final RxEventBus rxEventBus = new RxEventBus();
public static RxEventBus provide(){
return rxEventBus;
}
}
RxEventBusProvider.java
※ providing the singleton instance
10. public class RxEventBus {
private final Subject<Object, Object> subject
= new SerializedSubject<>(PublishSubject.create());
public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.subscribe(handler);
}
public <T> Subscription onEventMainThread(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(handler);
}
public void post(Object event) {
subject.onNext(event);
}
}
Subscribing in the main thread
11. public class ChangedEvent {
private int id;
public ChangedEvent(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
rxEventBus.post(new ChangedEvent(99));
rxEventBus.onEvent(ChangedEvent.class, event -> {
int id = event.getId();
// something..
});
Getting a value from the event
14. @Module
public class AppModule {
@Provides
@Singleton
public RxEventBus provideRxEventBus(){
return new RxEventBus();
}
}
AppModule.java
@Component(modules = AppModule.class)
public interface AppComponent {
RxEventBus provideRxEventBus();
}
AppComponent.java
15. Getting instance
AppComponent appComponent = DaggerAppComponent.create();
// ...
RxEventBus rxEventBus = appComponent.provideRxEventBus();
In this example, Dagger2 looks redundant , but
redundant description can be reduced by
@inject annotation to the constructor.
See https://github.com/hkusu/android-dagger-rxjava-sample .