startWith

签名: startWith(an: Values): Observable

发出给定的第一个值


:bulb: BehaviorSubject 也可以从初始值开始!


startWith - 图2

示例

( 示例测试 )

示例 1: 对数字序列使用 startWith

( StackBlitz |
jsBin |
jsFiddle )

  1. import { startWith } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. // 发出 (1,2,3)
  4. const source = of(1, 2, 3);
  5. // 从0开始
  6. const example = source.pipe(startWith(0));
  7. // 输出: 0,1,2,3
  8. const subscribe = example.subscribe(val => console.log(val));
示例 2: startWith 用作 scan 的初始值

( StackBlitz | |
jsBin |
jsFiddle )

  1. import { startWith, scan } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. // 发出 ('World!', 'Goodbye', 'World!')
  4. const source = of('World!', 'Goodbye', 'World!');
  5. // 以 'Hello' 开头,后面接当前字符串
  6. const example = source.pipe(
  7. startWith('Hello'),
  8. scan((acc, curr) => `${acc} ${curr}`)
  9. );
  10. /*
  11. 输出:
  12. "Hello"
  13. "Hello World!"
  14. "Hello World! Goodbye"
  15. "Hello World! Goodbye World!"
  16. */
  17. const subscribe = example.subscribe(val => console.log(val));
示例 3: 使用多个值进行 startWith

( StackBlitz |
jsBin |
jsFiddle )

  1. import { startWith } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. // 每1秒发出值
  4. const source = interval(1000);
  5. // 以 -3, -2, -1 开始
  6. const example = source.pipe(startWith(-3, -2, -1));
  7. // 输出: -3, -2, -1, 0, 1, 2....
  8. const subscribe = example.subscribe(val => console.log(val));

相关食谱

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/startWith.ts