rxjs 里 CombineLatest 操作符的一个使用场景
一个 场景 操作符 Rxjs 使用
2023-09-14 09:04:00 时间
一个具体的例子:
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 所以多个空值也不会通过。
这里涉及到的知识点:
- 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
- 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.
相关文章
- 记一个AbstractMethodError
- JSP的一个增删改查例子和总结
- Java核心知识点学习----线程中如何创建锁和使用锁 Lock,设计一个缓存系统
- 一个超好用的Web SQL查询工具~
- Atitit spring注解事务的demo与代码说明 目录 1.1. Spring框架中,要如何实现事务?有一个注解,@EnableTransactionManagement1 1.2. 事务管理
- OpenCV使用brisk做一个简单的场景匹配
- Nagios显示器MySQL一个错误:NRPE: Unable to read output具体的解决过程
- 【Spring注解驱动开发】你敢信?面试官竟然让我现场搭建一个AOP测试环境!
- mumu血压计母亲节“拼团”盛大开幕,百度和厂家创造一个双赢的局面
- Linux下一个Nginx安装步骤
- 秒杀多线程第四篇 一个经典的多线程同步问题
- LCC编译器的源程序分析(50) 分配一个寄存器