当我在代码下面运行时,如果我不写observeOn
行,应用程序会崩溃,因为getView().showBlockLayout(isBlock);
调用了一个尝试隐藏或显示布局的方法。但我试图在下面更改observeOn(AndroidSchedulers.mainThread())
为subscribeOn(AndroidSchedulers.mainThread())
应用程序再次崩溃!
subscription.add(UserStore.getInstance().getBlockObservable(databaseHelper.getConference().getUserChatId())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean isBlock) {
getView().showBlockLayout(isBlock);
databaseHelper.getConference().setBlock(isBlock);
mConferenceModel.setBlock(isBlock);
}
}));
我也对此进行测试:
subscription.add(UserStore.getInstance().getBlockObservable(databaseHelper.getConference().getUserChatId())
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean isBlock) {
getView().showBlockLayout(isBlock);
databaseHelper.getConference().setBlock(isBlock);
mConferenceModel.setBlock(isBlock);
}
}));
出乎意料的是它起作用了并且没有崩溃!我没有在 getBlockObservable 方法中使用 subscribeOn(因为我知道我们可以设置一次)
这是我的UserStore
课
PublishSubject<Pair<String,Boolean>> mObservableBlock;
private UserStore(){
mObservableBlock = PublishSubject.create();
mInstance = this;
}
public static UserStore getInstance() {
if(mInstance == null)
new UserStore();
return mInstance;
}
public Observable<Boolean> getBlockObservable(final String userId){
return mObservableBlock
.observeOn(Schedulers.computation())
.filter(new Func1<Pair<String,Boolean>, Boolean>() {
@Override
public Boolean call(Pair<String,Boolean> s) {
if(userId.equals(s.first))
return true;
return false;
}
}).map(new Func1< Pair<String, Boolean>, Boolean>() {
@Override
public Boolean call(Pair<String, Boolean> UserBlock) {
return UserBlock.second;
}
});
}
public void publishBlockedUser(String userId,boolean isBlock){
mObservableBlock.onNext(new Pair<String, Boolean>(userId,isBlock));
}
这是我在 gradle 中导入 rxjava 依赖项的方式
compile 'io.reactivex:rxjava:1.1.5'
compile 'io.reactivex:rxandroid:1.2.0'