如何强制 observables 按顺序执行? [英] How to force observables to execute in sequence?

查看:84
本文介绍了如何强制 observables 按顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Promise 世界转移到 Observable 世界.我通常对 Promise 做的一件事是将一系列任务串联起来,并让它们按顺序运行.例如,我有三个任务:printLog1() 将 1 打印到控制台,printLog23() 将 2 和 3 打印到控制台,以及 printLog4() 打印 4.

I am moving from the Promise world to the Observable world. One thing I usually do with Promise is to chain a series of tasks and make them run in sequence. For example, I have three tasks: printLog1() to print 1 to the console, printLog23() to print 2 and 3 to the console, and printLog4() to print 4.

当我想打印 1-2-3-4 时,我会写一个像

When I want to print 1-2-3-4, I would write a promise chain like

printLog1()
  .then(() => {
    printLog23();
  })
  .then(() => {
    printLog4();
  });

现在我想要与 Observable 相同的功能,我可以将 printLog() 函数重写为 Observable 之类的

Now I want the same functionality with Observable and I can rewrite the printLog() function into an Observable like

printLog1 = Rx.Observabale.of(1).map((i) => console.log(i));
printLog23 = Rx.Observabale.of(2, 3).map((i) => console.log(i));
printLog4 = Rx.Observabale.of(4).map((i) => console.log(i));

然后我有三个 observable 向控制台发出不同的值.我如何将它们链接起来,以便这三个 observable 按顺序运行并打印 1-2-3-4?

Then I have three observables that emits different values to the console. How do I chain them so that these three observables would run in order and print 1-2-3-4?

推荐答案

如果您想确保排放顺序与您指定源 Observables 的顺序相同,您可以使用 concatconcatMap 运算符.

If you want to be sure the order of emissions is the same as the order in which you specified the source Observables you can use concat or concatMap operators.

concat* 操作符仅在前一个 Observable 完成后订阅 Observable(它也适用于 Promises,参见 http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObservableInputDoc.html).

The concat* operators subscribe to an Observable only after the previous Observable completes (it works with Promises as well, see http://reactivex.io/rxjs/class/es6/MiscJSDoc.js~ObservableInputDoc.html).

在你的情况下,它看起来像下面这样:

In you case it'd look like the following:

import { concat } from 'rxjs'; // Note, concat from 'rxjs', is not the same as concat from 'rxjs/operators'

concat(printLog1, printLog23, printLog4);

... 或者使用 concatMap 如果对一个 Promise 的请求依赖于前一个 Promise 的响应:

... or with concatMap if the request for one Promise depends on the response from the previous Promise:

printLog1.pipe(
  concatMap(response => ...),
  concatMap(response => ...),
);

...或者当顺序无关紧要时,您可以使用 merge 立即订阅所有 Observables/Promises 并在它们到达时重新发送它们的结果:

... or when the order doesn't matter you can use merge that subscribes to all Observables/Promises immediately and reemits their results as they arrive:

merge(printLog1, printLog23, printLog4);

2019 年 1 月:针对 RxJS 6 更新

Jan 2019: Updated for RxJS 6

这篇关于如何强制 observables 按顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆