配置
//引入rxJava
compile 'io.reactivex.rxjava2:rxjava:2.1.8'
//引入rxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//引入rxJava适配器,方便rxJava与retrofit的结合
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//引入rxrelay2,出现异常仍然可以处理
compile 'com.jakewharton.rxrelay2:rxrelay:2.0.0'
Rxbus封装
public class RxBus {
private final Relay<Object> mBus;
private RxBus() {
// toSerialized method made bus thread safe
mBus = PublishRelay.create().toSerialized();
}
public static RxBus get() {
return Holder.BUS;
}
//发送事件
public void post(Object obj) {
mBus.accept(obj);
}
//根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
public <T> Observable<T> toObservable(Class<T> tClass) {
return mBus.ofType(tClass);
}
public Observable<Object> toObservable() {
return mBus;
}
//判断是否有订阅者
public boolean hasObservers() {
return mBus.hasObservers();
}
private static class Holder {
private static final RxBus BUS = new RxBus();
}
}
RxBus使用
发送
OrgBean orgBean = new OrgBean();
RxBus.get().post(orgBean);
接收
RxBus.get().toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
if (o instanceof OrgBean) {
OrgBean mOrgBean = new OrgBean();
mOrgBean = ((OrgBean) o);
}
}
});
记录自己的android学习笔记。
欢迎互相学习Github
网友评论