startWith

signature: startWith(an: Values): Observable

Emit given value first.


:bulb: A
BehaviorSubject
can also start with an initial value!


startWith - 图2

Examples

(
example tests
)

Example 1: startWith on number sequence

( StackBlitz |
jsBin |
jsFiddle )

  1. import { startWith } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. //emit (1,2,3)
  4. const source = of(1, 2, 3);
  5. //start with 0
  6. const example = source.pipe(startWith(0));
  7. //output: 0,1,2,3
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: startWith for initial scan value

( StackBlitz | |
jsBin |
jsFiddle )

  1. import { startWith, scan } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. //emit ('World!', 'Goodbye', 'World!')
  4. const source = of('World!', 'Goodbye', 'World!');
  5. //start with 'Hello', concat current string to previous
  6. const example = source.pipe(
  7. startWith('Hello'),
  8. scan((acc, curr) => `${acc} ${curr}`)
  9. );
  10. /*
  11. output:
  12. "Hello"
  13. "Hello World!"
  14. "Hello World! Goodbye"
  15. "Hello World! Goodbye World!"
  16. */
  17. const subscribe = example.subscribe(val => console.log(val));
Example 3: startWith multiple values

( StackBlitz |
jsBin |
jsFiddle )

  1. import { startWith } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. //emit values in sequence every 1s
  4. const source = interval(1000);
  5. //start with -3, -2, -1
  6. const example = source.pipe(startWith(-3, -2, -1));
  7. //output: -3, -2, -1, 0, 1, 2....
  8. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


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