如何在RxScala / Java中使用多个线程执行map,filter,flatMap?

时间:2015-11-17 04:13:47

标签: scala concurrency functional-programming rx-java rx-scala

如何使用多个主题在filter上运行mapflatMapObservable

  def withDelay[T](delay: Duration)(t: => T) = {
    Thread.sleep(delay.toMillis)
    t
  }

  Observable
    .interval(500 millisecond)
    .filter(x => {
      withDelay(1 second) { x % 2 == 0 }
    })
    .map(x => {
      withDelay(1 second) { x * x }
    }).subscribe(println(_))

目标是使用多个线程同时运行过滤和转换操作。

2 个答案:

答案 0 :(得分:0)

Yo可以在每个操作上使用Async.toAsync()。

它在包rxjava-async

Documentation

答案 1 :(得分:0)

您必须使用 observeOn 运算符,它将在设置运算符后定义的特定线程中执行所有下一个运算符

       /**
 * Once that you set in your pipeline the observerOn all the next steps of your pipeline will be executed in another thread.
 * Shall print
 * First step main
 * Second step RxNewThreadScheduler-2
 * Third step RxNewThreadScheduler-1
 */
@Test
public void testObservableObserverOn() throws InterruptedException {
    Subscription subscription = Observable.just(1)
            .doOnNext(number -> System.out.println("First step " + Thread.currentThread()
                    .getName()))
            .observeOn(Schedulers.newThread())
            .doOnNext(number -> System.out.println("Second step " + Thread.currentThread()
                    .getName()))
            .observeOn(Schedulers.newThread())
            .doOnNext(number -> System.out.println( "Third step " + Thread.currentThread()
                    .getName()))
            .subscribe();
    new TestSubscriber((Observer) subscription)
            .awaitTerminalEvent(100, TimeUnit.MILLISECONDS);
}

此处有更多异步示例https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/scheduler/ObservableAsynchronous.java