4

如何运行filtermap以及flatMap使用Observable多个线程:

  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(_))

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

4

3 回答 3

0

这将在不同的线程 (rxjava3) 中处理每个集合项。

var collect = Observable.fromIterable(Arrays.asList("A", "B", "C"))
                      .flatMap(v -> {
                         return Observable.just(v)
                                        .observeOn(Schedulers.computation())
                                        .map(v1 -> {
                                            int time = ThreadLocalRandom.current().nextInt(1000);
                                            Thread.sleep(time);
                                            return String.format("processed-%s", v1);
                                        });
                      })
                      .observeOn(Schedulers.computation())
                      .blockingStream()
                      .collect(Collectors.toList());
于 2021-08-18T13:31:53.980 回答
0

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

它在包 rxjava-async

文档

于 2016-07-20T20:24:15.673 回答
-1

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

于 2016-07-21T08:03:20.177 回答