startWith
签名: startWith(an: Values): Observable
发出给定的第一个值
BehaviorSubject 也可以从初始值开始!
示例
( 示例测试 )
示例 1: 对数字序列使用 startWith
( StackBlitz |
jsBin |
jsFiddle )
import { startWith } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
// 发出 (1,2,3)
const source = of(1, 2, 3);
// 从0开始
const example = source.pipe(startWith(0));
// 输出: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));
示例 2: startWith 用作 scan 的初始值
( StackBlitz | |
jsBin |
jsFiddle )
import { startWith, scan } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
// 发出 ('World!', 'Goodbye', 'World!')
const source = of('World!', 'Goodbye', 'World!');
// 以 'Hello' 开头,后面接当前字符串
const example = source.pipe(
startWith('Hello'),
scan((acc, curr) => `${acc} ${curr}`)
);
/*
输出:
"Hello"
"Hello World!"
"Hello World! Goodbye"
"Hello World! Goodbye World!"
*/
const subscribe = example.subscribe(val => console.log(val));
示例 3: 使用多个值进行 startWith
( StackBlitz |
jsBin |
jsFiddle )
import { startWith } from 'rxjs/operators';
import { interval } from 'rxjs/observable/interval';
// 每1秒发出值
const source = interval(1000);
// 以 -3, -2, -1 开始
const example = source.pipe(startWith(-3, -2, -1));
// 输出: -3, -2, -1, 0, 1, 2....
const subscribe = example.subscribe(val => console.log(val));
相关食谱
其他资源
- startWith - 官方文档
- 使用 startWith 显示初始值 - John Linquist
- 当加载时使用 startWith 清除数据 - André Staltz
- 组合操作符: concat, startWith - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/startWith.ts