封裝base的時候想到事件分發(fā) 既然用到了Rxjava 很神奇的發(fā)現(xiàn)了Rxbus這個東西贷腕,那就學(xué)習(xí)下~
Github:https://github.com/balckban/RxbusDemo-RxJava2.0-
- 首先是gradle的配置
compile "io.reactivex.rxjava2:rxjava:2.1.3"
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
- RxBus寫法
背壓式處理 很詳細http://flyou.ren/2017/04/05/關(guān)于RxJava背壓/
1.沒有做背壓式處理
private final Subject<Object> _bus;
private static class RxHolder{
private static volatile RxBus sRxBus = new RxBus();
}
private RxBus() {
_bus = PublishSubject.create().toSerialized();
}
public static RxBus getInstance(){
return RxHolder.sRxBus;
}
public void send(Object o){
if (hasObserve()) {
_bus.onNext(o);
}
}
private boolean hasObserve() {
return _bus.hasObservers();
}
public Observable<Object> toObservable(){
return _bus;
}
// 根據(jù)傳入的事件類型,返回特定類型的eventType的被觀察者
public <T extends Object> Observable<T> toObservable(Class<T> event){
return _bus.ofType(event);
}
2.背壓式處理代碼
private final FlowableProcessor<Object> _bus;
private RxBus() {
// toSerialized method made bus thread safe
_bus = PublishProcessor.create().toSerialized();
}
public static RxBus getInstance() {
return Holder.BUS;
}
public void send(Object obj) {
_bus.onNext(obj);
}
/**
* 根據(jù)傳遞的 eventType 類型返回特定事件類型的被觀察者
*/
public <T> Flowable<T> toFlowable(Class<T> tClass) {
return _bus.ofType(tClass);
}
public Flowable<Object> toFlowable() {
return _bus;
}
public boolean hasSubscribers() {
return _bus.hasSubscribers();
}
private static class Holder {
private static final RxBus BUS = new RxBus();
}
3.Rxbus使用
接收
RxBus.getInstance().toFlowable(輸入自己特定的class 比如TestEvent.class 區(qū)分事件).subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
Toast.makeText(MainActivity.this, "已發(fā)送", Toast.LENGTH_SHORT).show();
if (((TestEvent) o).getTest() != null) {
mTvReceive.setText(((TestEvent) o).getTest());
}
}
});
}
發(fā)送
mBtnReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RxBus.getInstance().send(new TestEvent(mEtNext.getText().toString()));
finish();
}
});