Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava, execute code in the observer thread before chaining two observables

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?

like image 750
Dr NotSoKind Avatar asked Apr 16 '15 08:04

Dr NotSoKind


People also ask

What's the difference between observeOn () and subscribeOn ()?

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.

How does RxJava chain work?

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.

Is RxJava multithreaded?

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.

What is OnNext in RxJava?

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.


1 Answers

Rxjava has a doOnNext operator which is what you're looking for.

like image 93
dwursteisen Avatar answered Sep 29 '22 15:09

dwursteisen