我想在RxJava中连续运行两个步骤。我希望第一步在第二步开始之前完成,例如:
step 1: start
step 1: finish
step 2: start
step 2: finish我正在尝试不同的API变体,RxJava并行运行我的两个步骤,这不是我想要的行为:
step 1: start
step 2: start
step 2: finish
step 1: finish在下面的代码示例中,我尝试了andThen和defer,并得到了并行执行。如何解决这个问题,使一个步骤在另一个步骤成功完成后执行?
方法名andThen意味着顺序串行执行。方法defer接受一个函数,该函数产生另一个可完成的函数,这是我所希望的串行任务执行的方法签名。也不要给我我想要的结果。
我需要转换成可观察的/流动的吗?或者我可以用可完成的方式连锁两个步骤?
public class RxStep1Then2 {
public static Completable simulateCompletable(ScheduledExecutorService es, String msg, int msDelay) {
System.out.println(String.format("%s: start", msg));
ScheduledFuture<?> future = es.schedule(() -> {
System.out.println(String.format("%s: finish", msg));
}, msDelay, TimeUnit.MILLISECONDS);
return Completable.fromFuture(future);
}
public static void rxMain(ScheduledExecutorService es) {
// Completable c = simulateCompletable(es, "step 1", 1000)
// .andThen(simulateCompletable(es, "step 2", 500));
Completable c = simulateCompletable(es, "step 1", 1000)
.defer(() -> simulateCompletable(es, "step 2", 500));
c.blockingAwait();
System.out.println("blockingAwait done");
}
public static void main(String[] args) throws Exception {
ScheduledExecutorService es = Executors.newScheduledThreadPool(5);
System.out.println("Started ExecutorService.");
rxMain(es);
es.shutdown();
es.awaitTermination(5, TimeUnit.MINUTES);
System.out.println("Shutdown ExecutorService. Done.");
}
}发布于 2017-10-17 21:58:10
并行执行之所以发生,是因为您的simulateCompletable在创建Completable之前就启动了任务。您可以直接使用延迟的Completable:
Completable.fromAction(() -> System.out.println("First"))
.delay(1, TimeUnit.SECONDS)
.andThen(Completable.fromAction(() -> System.out.println("Second")))
.blockingAwait();请注意,
Completable c = simulateCompletable(es, "step 1", 1000)
.defer(() -> simulateCompletable(es, "step 2", 500));不链接任何操作,因为defer是一个静态工厂方法,可以创建一个独立的Completable;第一个simulateCompletable的Completable就是丢失的。
https://stackoverflow.com/questions/46799783
复制相似问题