public class RxBus {
private static volatile RxBus defaultInstance;
private final Subject<Object, Object> bus;
public RxBus() {
bus = new SerializedSubject<>(PublishSubject.create());
}
// 单例RxBus
public static RxBus getDefault() {
RxBus rxBus = defaultInstance;
if (defaultInstance == null) {
synchronized (RxBus.class) {
rxBus = defaultInstance;
if (defaultInstance == null) {
rxBus = new RxBus();
defaultInstance = rxBus;
}
}
}
return rxBus;
}
public void send(Object o) {
bus.onNext(o);
}
public <T> Observable<T> toObservable(Class<T> eventClass) {
return bus.ofType(eventClass);
}
}
发送Event
RxBus.getDefault().send(new StatusBarEvent());
接受Event
Subscription rxSubscription = RxBus.getDefault().toObservable(StatusBarEvent.class)
.subscribe(new Action1<StatusBarEvent>() {
@Override
public void call(StatusBarEvent statusBarEvent) {
//do something
}
});
注销
@Override
protected void onDestroy() {
super.onDestroy();
if (!rxSubscription.isUnsubscribed()) {
rxSubscription.unsubscribe();
}
IMainPresenter.unsubcrible();
}