简体   繁体   English

rxJava:如何同时执行多个Maybe

[英]rxJava: how to execute multiple Maybes simultaneously

I want to merge three Maybes together, as follows:我想将三个Maybes合并在一起,如下:

return Maybe.merge(
    aOneSecondTask(),
    aFiveSecondTask(),
    aTenSecondTask()
).firstElement();

Each of the tasks does a Thread.sleep() for the appropriate amount of time, then logs the current time just before returning.每个任务都会在适当的时间内执行Thread.sleep() ,然后在返回之前记录当前时间。

When I run this code, the logs look like this:当我运行此代码时,日志如下所示:

Starting at 13:26:38
Finishing one-second task at 13:26:39
Finishing five-second task at 13:26:44
Finishing ten-second task at 13:26:54

The docs for Maybe suggest that this method should run all the Maybes at once. Maybe 的文档建议此方法应一次运行所有 Maybes。 I'd therefore expect the entire thing to take no more than 10 seconds.因此,我希望整个过程不会超过 10 秒。 Instead, it takes 16 seconds - each task doesn't start until the previous one is finished.相反,它需要 16 秒 - 每个任务在前一个任务完成之前不会开始。

How can I fire off all three tasks simultaneously?如何同时启动所有三个任务?

You probably have only a single-threaded scheduler, so while your Maybe s are scheduled to run concurrently, they actually run in series.您可能只有一个单线程调度程序,因此当您的Maybe被调度为并发运行时,它们实际上是串联运行的。 Don't use blocking calls like Thread.sleep() in a reactive environment.不要在反应式环境中使用像Thread.sleep()这样的阻塞调用。 In this case, as you are just simulating a slow process, use something like delay() to add the required delay to each Maybe .在这种情况下,由于您只是在模拟一个缓慢的过程,因此请使用delay()之类的方法为每个Maybe添加所需的延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM