0

I have the following code in which I am using a few methods from rxJava api like buffer, observable from iterable, and parallization. I get inspired by this post: RxJava and parallel execution of observer code and I am almost sure I did it as https://stackoverflow.com/users/1011435/lordraydenmk has explained in his post, but my code is still executed sequentially in main thread;/ anybody can help me figure out what I am doing wrong here?

Thanks in advance!

private static Observable<String> getPositions(List<String> id) throws InterruptedException {
    System.out.println("thread: " + Thread.currentThread().getName());
    Thread.sleep(500);
    return Single.fromCallable(() -> {
        if (id.contains("3")) {
            return Arrays.asList("a", "aa", "aaa");
        } else if (id.contains("2")) {
            return Arrays.asList("b", "bb", "bbb");
        }
        return Arrays.asList("c", "cc", "ccc");
    }).flatMapObservable(Observable::fromIterable).subscribeOn(Schedulers.computation());
}

public static void main(String[] args) throws InterruptedException {

    Observable<String> a = Observable.fromIterable(Arrays.asList("1", "2", "3"));

    a.buffer(2).flatMap(buff -> getPositions(buff), 4).toList().subscribe(val -> System.out.println(val));

    Thread.sleep(1500);
}

the output is:

thread: main
thread: main
[b, bb, bbb, a, aa, aaa]
2
  • You need to print the thread inside Single.fromCallable. The getPositions function is called on the main thread. subscribeOn changes the scheduler for the observable. Commented Oct 28, 2021 at 18:33
  • OMG, thanks for help! Commented Oct 28, 2021 at 18:39

0

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.