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

如何在RxScala/Java中使用多个线程执行map、filter、flatMap?,scala,concurrency,functional-programming,rx-java,rx-scala,Scala,Concurrency,Functional Programming,Rx Java,Rx Scala,如何使用多个线程在Observable上运行filter、map和flatMap: def withDelay[T](delay: Duration)(t: => T) = { Thread.sleep(delay.toMillis) t } Observable .interval(500 millisecond) .filter(x => { withDelay(1 second) { x % 2 == 0 } }

如何使用多个线程在
Observable
上运行
filter
map
flatMap

  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(_))
目标是使用多个线程同时运行筛选和转换操作。

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

它在rxjavaasync包中


您必须使用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);
}

这里有更多的异步示例

你看了吗:@david.mihola,是的,我检查了这两个示例,并且能够在多个线程中执行
subscribe
block,但是对于map、flatMap和filter,我不能这样做。我假设在过滤或转换时,我可能会调用其他API或从数据库获取额外数据,因此我希望确保此代码将同时执行。是的,但如果使用.doOnNext(),则不能执行映射、展开等操作。这只是接受操作。举个例子,您应该能够使用任何运算符