RxJava:How to do some process before subscribe
I have a class like this:
Code1:
class Container {
boolean success;
List<Book> books;
}
I want to change code:
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();
}
});
to
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();
}
}
});
Is this the right way to do this?
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);
});
Question is:
1.should I use method filter()
?
2.which is the filter block run on? UI_Thread
or IO_Thread
?
3.is Code3 can be simply to Code4 ?
and sorry for my poor english.
maybe, you can use doOnNext
and lift
with your custom operator
.
class ContainerCheck implements Observable.Operator<Container, Container> {
@Override
public Subscriber<? super Container> call(Subscriber<? super Container> o) {
return new Subscriber<Container>() {
@Override
public void onCompleted() {
if (o.isUnsubscribed()) return;
o.onCompleted();
}
@Override
public void onError(Throwable e) {
if (o.isUnsubscribed()) return;
o.onError(e);
}
@Override
public void onNext(Container container) {
if (o.isUnsubscribed()) return;
if (container.success) {
o.onNext(container);
} else {
o.onError(new Throwable("your costom exception"));
}
}
};
}
}
use ContainerCheck
with lift
.
Observable.just(createContainer(true))
.subscribeOn(Schedulers.io())
.lift(new ContainerCheck())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(container -> doSomethingWhenSuccess())
.map(container -> container.books)
.flatMap(Observable::from)
.subscribe(book -> {
doSomethingForBook(book);
}, e -> doSomethingWhenFail());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With