public class RxBus {
public RxBus() {
}
private PublishSubject<Object> bus = PublishSubject.create();
public void send(Object o) {
bus.onNext(o);
}
public Observable<Object> toObservable() {
return bus;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}
在你的Application
public class MyApplication extends Application {
public static final String TAG = "MyApplication";
private RxBus bus;
@Override
public void onCreate() {
super.onCreate();
bus = new RxBus();
}
public RxBus bus() {
return bus;
}
public void sendAutoEvent() {
Observable.timer(2, TimeUnit.SECONDS)
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
bus.send(new Events.AutoEvent());
}
});
}
}
你发送的时候
((MyApplication) getApplication()).sendAutoEvent();
需要的时候
disposables.add(((MyApplication) getApplication())
.bus()
.toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object object) throws Exception {
if (object instanceof Events.AutoEvent) {
textView.setText("Auto Event Received");
} else if (object instanceof Events.TapEvent) {
textView.setText("Tap Event Received");
}
}
}));
<pre>
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MyApplication) getApplication())
.bus()
.send(new Events.TapEvent());
}
});
</pre>
网友评论