1
當我運行下面的代碼時,如果我不寫observeOn
行,應用程序崩潰,因爲getView().showBlockLayout(isBlock);
調用試圖隱藏或顯示佈局的方法。 但我試圖改變observeOn(AndroidSchedulers.mainThread())
以下至subscribeOn(AndroidSchedulers.mainThread())
和應用程序崩潰!爲什麼onSubscribe在rxjava中不起作用?
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'
當您更改the'.observeOn(AndroidSchedulers.mainThread())''來subscribeOn'(和它仍然崩潰)是什麼你傳遞到'subscribeOn'調用的參數? – theFunkyEngineer
@theFunkyEngineer subscribeOn(AndroidSchedulers.mainThread())如果我沒有observeOn它崩潰 –
它崩潰,因爲我試圖改變UI線程中的東西 –