0

New to RxJava and Reactive Programming so to speak.

I'm trying to map two functions in parallel as part of a single Observable pipeline, but doesn't seem to work this way. Here is my code.

Observable.fromCallable(thatReturnsNumberOne())
                .observeOn(newThread())
                .map(doubleIt())
                .observeOn(newThread())
                .map(doubleIt())
                .subscribe(testSubscriber);

I'd like the 2 doubleIt() calls to be spawned at the same time. But it always appears to be that once the first doubleIt() finishes, only then the second one starts. ie blocking/sequential.

What am I missing?

1 Answer 1

1

I'm assuming thatReturnsNumberOne() only returns a single value. The value that is returned is passed to each of the operators in sequence. By using observeOn(newThread()) your only changing to a new thread when the value gets to that point in the chain.

If you want to do calculations in parallel, you have to use multiple observables:

Observable.fromCallable(thatReturnsNumberOne())
    .flatMap(number -> Observable.fromCallable(doubleIt(number)).subscribeOn(newThread())
        .combineLatest(Observable.fromCallable(doubleIt(number)).subscribeOn(newThread()),
        doubles -> doubles[0] + doubles[1]))
    .subscribe(testSubscriber);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.