如何并行执行 2 个 Observable,忽略它们的结果并执行下一个 Observable [英] How to execute 2 Observables in parallel, ignoring their results and execute next Observable
问题描述
我必须并行执行 2 个 observable(不关心它们的输出),当它们都完成时 -> 运行另一个 observable.
I have to execute 2 observable in parallel (don't care about their output), and when they both finished -> run another observable.
这是我的解决方案,但我觉得还有更好的:
This is my solution, but I feel there are better ones:
rx.Observable<GameObject> obs1 = ...;
rx.Observable<GameObject> obs2 = ...;
rx.Observable.merge(obs1,obs2).takeLast(1)
.flatMap(mergeObj -> {
return payoutStrategy.calculatePayout(gameTemplate, gameData);
}).subscribe(results -> {
...
});
我使用合并只是为了调用 2 个 obs,然后使用 'takeLast(1)' 忽略两次输入 'flatMap'.
I use merge just in order to invoke the 2 obs's and then 'takeLast(1)' to ignore entering 'flatMap' twice.
这个解决方案远非优雅但有效..
This solution is far from being elegant but it works..
有什么想法可以让它变得更好吗?
Any ideas how to make it better?
谢谢!
推荐答案
concat
可用于在完成其他事情后做某事.由于 calculatePayout
返回的 Observable
类型可能不同,因此您将空流转换为其结果类型:
concat
is useful for doing something on completion of something else. Because the type of Observable
returned by calculatePayout
is presumably different you cast the empty stream to its result type:
obs1.mergeWith(obs2)
.ignoreElements()
.castAs(Payout.class)
.concatWith(payoutStrategy.calculatePayout(gameTemplate, gameData))
.subscribe( ...)
顺便说一下,如果 obs1
和 obs2
不是异步源,那么你可以这样做以确保 obs1
和 obs2
并行运行:
By the way if obs1
and obs2
are not async sources already then you can do this to ensure obs1
and obs2
are run in parallel:
obs1.subscribeOn(scheduler).mergeWith(obs2.subscribeOn(scheduler))
...
取决于 obs2
正在做什么 scheduler
可能是 Scheduler.computation()
或 Schedulers.io()
>.
Depending on what obs2
is doing scheduler
might be Schedulers.computation()
or Schedulers.io()
.
对于多个源 observables,您也可以这样做:
For multiple source observables you can also do this:
Observable.just(obs1, obs2, .. , obsN)
.flatMap(o -> o.subscribeOn(Schedulers.computation())
.ignoreElements()
...
这篇关于如何并行执行 2 个 Observable,忽略它们的结果并执行下一个 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!