likes
comments
collection
share

rxjs 里 CombineLatest 操作符的一个使用场景

作者站长头像
站长
· 阅读数 17

一个具体的例子:

combineLatest([
  data$.pipe(startWith(null)),
  loading$,
]).pipe(
  takeWhile(([data, loading]) => !data || loading, true),
  map(([data, loading]) => loading ? null : data),
  skip(1),
  distinctUntilChanged(),
);

我们在这里使用巧妙的 takeWhile 函数。 它只会让带有虚假数据(falsy data)(初始 null )或 truthy loading 的发射值通过,这正是我们需要显示 spinner 的时候。 当条件不满足时,由于第二个参数,我们也让最终值通过。

然后我们使用 map 函数映射结果。 如果 loading 标志位为 true,则 map 返回的值为 null,这很合理,因为 loading 的时候是肯定没有数据返回的。当 loading 标志位为 false,说明数据返回完毕,则返回真实的 data.

我们使用 skip(1) 是因为我们不希望我们的 startWith(null) 数据流通过。 我们使用 distinctUntilChanged 所以多个空值也不会通过。

这里涉及到的知识点:

  1. startWith

一个例子:

// RxJS v6+
import { startWith } from 'rxjs/operators';
import { of } from 'rxjs';

//emit (1,2,3)
const source = of(1, 2, 3);
//start with 0
const example = source.pipe(startWith(0));
//output: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));

上面的 example 订阅后,会打印通过 startWith 传入的初始值 0,然后是 of 包裹的1,2,3

  1. takeWhile

这个 Operator 会持续发射数据,直接传入的条件不满足,则终止数据 emit.

注意 takeWhile 和 filter 的区别在于,前者在遇到 condition 为 false 时,会 fire 一个 complete 事件,而后者不会。

下面是一个具体的比较:

// RxJS v6+
import { of } from 'rxjs';
import { takeWhile, filter } from 'rxjs/operators';

// emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
const source$ = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);

// allow values until value from source equals 3, then complete
source$
  .pipe(takeWhile(it => it === 3))
  // log: 3, 3, 3
  .subscribe(val => console.log('takeWhile', val));

source$
  .pipe(filter(it => it === 3))
  // log: 3, 3, 3, 3, 3, 3, 3
  .subscribe(val => console.log('filter', val));

takeWhile 在遇到 of Observable 里第四个元素即 9 时,就会 fire complete 事件,因此 of Observable 余下的所有元素,再没有被 emit 的机会,而 filter 则不然,最后会打印 of Observable 里所有的元素 3.

rxjs 里 CombineLatest 操作符的一个使用场景