[Rxjs] Observable.concat()的使用

https://rxjs-dev.firebaseapp.com/api/index/function/concat

使用场景:需要同时触发n个请求后端顺序,且要一个个返回结果并处理结果。Promise.all()不合适,因为它要等所有结果都返回了才会返回给前端,这样造成页面等待时间过长,用户体验不佳。比较好的体验结果应该是看到页面上的结果一个个被更新。 犹如jenkins build好多job。看它们一个个build结束。

这个时候就要用到Observable.concat(),这是官网对它的定义。

Creates an output Observable which sequentially emits all values from given Observable and then moves on to the next.
concat, R>(...observables: (SchedulerLike | O)[]): Observable | R>

concat will subscribe to first input Observable and emit all its values, without changing or affecting them in any way. When that Observable completes, it will subscribe to then next Observable passed and, again, emit its values. This will be repeated, until the operator runs out of Observables.

concat joins multiple Observables together, by subscribing to them one at a time and merging their results into the output Observable. You can pass either an array of Observables, or put them directly as arguments. Passing an empty array will result in Observable that completes immediately.
虽然文档说可以pass an array of Observables, 但实践证明它只收单个observable, 就像这样

Observable.concat(ob1, ob2, ob3).subscribe()

所以,你可以用for 构造一个observable 数组,然后用扩展运算符"..." 把数组打散成一个个变量传给concat.就像这样:

getLastBuild(){
  let observables: Observable[] = [];
  for (let key of Object.keys(jobGroup)) {
            let jobs = uniq(map(jobGroup[key], 'jenkinsJob'));
            observables.push(service.getJobLastBuild({jobNames: jobs}, key));
   }
  Observable.concat(...observables).subscribe(
            res => {
            //deal with the result one by one
            },
            err=>{},
            ()=>{}
}  

如果你不懂扩展运算符(数组前面的三个点), 可以参考
https://es6.ruanyifeng.com/#docs/array#%E6%89%A9%E5%B1%95%E8%BF%90%E7%AE%97%E7%AC%A6

扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

[...document.querySelectorAll('div')]
// [

,
,
]

===============额外知识:如果你也用golang===============
golang也用...用于打散slice以便追加到另一个slice上,只是golang是放在变量后面,比如

var allChanges []string
changes:=getChanges()
allChanges=append(allChanges,changes...)

但golang的...不仅仅这个作用,它还用于表达函数有多个不定参数(类型固定了)的情况:

func print(args ...string) { //可以接受任意个string参数
    for _, v:= range args{
        fmt.Println(v)
    }
}

你可能感兴趣的:([Rxjs] Observable.concat()的使用)