2
RxJava:如何做一些處理訂閱RxJava:如何做一些處理前訂閱
之前,我有一個這樣的類:
Code1:
class Container {
boolean success;
List<Book> books;
}
我想改變代碼:
Code2:
Observable.just(createContainer())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(container -> {
if (container.success) {
doSomethingWhenSuccess();
for (Book book : container.books) {
doSomethingForBook(book);
}
} else {
doSomethingWhenFail();
}
});
到
Code3:
Observable.just(createContainer())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Container>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
doSomethingWhenFail();
}
@Override
public void onNext(Container container) {
if (container.success) {
doSomethingWhenSuccess();
Observable.from(container.books)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(book -> {
doSomethingForBook(book);
});
} else {
doSomethingWhenFail();
}
}
});
是這個正確的方式來做到這一點?
Code4:
Observable.just(createContainer())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.filter(container -> { //step 2
if (container.success) {
doSomethingWhenSuccess();
} else {
doSomethingWhenFail();
}
return container.success;
})
.flatMap(container -> Observable.from(container.books))
.subscribe(book -> {
doSomethingForBook(book);
});
的問題是:
1.should我用的方法filter()
?
2.哪個過濾塊運行? UI_Thread
或IO_Thread
?
3.is Code3可以簡單地代碼4?
對不起,我的英語不好。
這是很不清楚你問什麼,什麼不工作。 –