如何使用多个主题在filter
上运行map
,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(_))
目标是使用多个线程同时运行过滤和转换操作。
答案 0 :(得分:0)
答案 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);
}