如何在Android上使用RxJava在多个线程上运行subsciber

时间:2015-10-21 19:57:06

标签: android multithreading rx-java rx-android

我是RxJava的新手并且在(我猜)简单问题上苦苦挣扎。我想在3个线程中处理订阅部分simuleasly。这就是我使用FixedThreadPool的原因。示例代码:

Observer.just("one", "two", "three", "four")
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.from(Executors.newFixedThreadPool(3))
.subscribe(new Observer<String>() {

    public void onNext(String string) {
        Log.d(TAG, "Started: " + string);
        SystemClock.sleep(1000);
        Log.d(TAG, "Ended: " + string);
    }

    (...)

}

预期结果:

Started: one
Started: two
Started: three
Ended: one
Started: four
Ended: two
Ended: three
Ended: four

实际结果:

Started: one
Ended: one
Started: two
Ended: two
Started: three
Ended: three
Started: four
Ended: four

我做错了什么?

1 个答案:

答案 0 :(得分:5)

RxJava Observable是顺序的,subscribeOnobserveOn运算符不会相互并行运行值。

您可以实现的最接近的事情是通过模数键对值进行分组,通过observeOn运行它们并合并结果:

AtomicInteger count = new AtomicInteger();

Observable.range(1, 100)
.groupBy(v -> count.getAndIncrement() % 3)
.flatMap(g -> g
    .observeOn(Schedulers.computation())
    .map(v ->  Thread.currentThread() + ": " + v))
.toBlocking()
.forEach(System.out::println);