I'm using RxJava and RxAndroid, and I want to combine two observables but in between I need to update the UI, so I must execute code in the main thread before reaching the subscriber.
One solution, instead of flatmapping (is that an accepted term?) two observables, would be to call the next observable in the subscriber just after updating the UI, but I feel that there should be a more elegant solution like:
myObservable
.map(new Func1<Object, Object>() {
@Override
public Object call(Object object) {
/* do stuff on the main thread */
return object;
}
})
.flatMap(new Func1<Object, Observable<OtherObject>>() {
@Override
public Observable<OtherObject> call(Object o) {
return new MyOtherObservable(o);
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
Of course, probably map is not the operator I need to use here. So, is there an operator or a better way to achieve this? Or am I missing the point about how observables should work?
observeOn() simply changes the thread of all operators further Downstream. People usually have this misconception that observeOn also acts as upstream, but it doesn't. subscribeOn() only influences the thread which is going to be used when Observable is going to get subscribed to and it will stay on it downstream.
It changes the thread as many times as you write it. flatMap starts the chain only during root chain data emission. No actions are performed during the root stream subscription process. Operators interval/delay/timer subscribe to computation under the hood, by default.
RxJava is NOT Multi-Threaded by Default RxJava, by default, is not multi-threaded in any way. The definition given for RxJava on their official website is as follows: A library for composing asynchronous and event-based programs using observable sequences for the Java VM.
OnNext. conveys an item that is emitted by the Observable to the observer. OnCompleted. indicates that the Observable has completed successfully and that it will be emitting no further items.
Rxjava has a doOnNext operator which is what you're looking for.
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