startWith
优质
小牛编辑
133浏览
2023-12-01
startWith
函数签名: startWith(an: Values): Observable
发出给定的第一个值
BehaviorSubject 也可以从初始值开始!
示例
( 示例测试 )
示例 1: 对数字序列使用 startWith
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { startWith } from 'rxjs/operators';
import { of } from 'rxjs';
// 发出 (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 )
// RxJS v6+
import { startWith, scan } from 'rxjs/operators';
import { of } from 'rxjs';
// 发出 ('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 )
// RxJS v6+
import { startWith } from 'rxjs/operators';
import { interval } from 'rxjs';
// 每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 :newspaper: - 官方文档
- 使用 startWith 显示初始值 :video_camera: :dollar: - John Linquist
- 当加载时使用 startWith 清除数据 :video_camera: :dollar: - André Staltz
- 组合操作符: concat, startWith :video_camera: :dollar: - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/startWith.ts