startWith

연산자(operator) 정의: startWith(an: Values): Observable

Emit given value first.


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


Examples

( example tests )

Example 1: startWith on number sequence

( jsBin | jsFiddle )

//emit (1,2,3)
const source = Rx.Observable.of(1,2,3);
//start with 0
const example =  source.startWith(0);
//output: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));
Example 2: startWith for initial scan value

( jsBin | jsFiddle )

//emit ('World!', 'Goodbye', 'World!')
const source = Rx.Observable.of('World!', 'Goodbye', 'World!');
//start with 'Hello', concat current string to previous
const example = source
  .startWith('Hello')
  .scan((acc, curr) => `${acc} ${curr}`);
/*
  output:
  "Hello"
  "Hello World!"
  "Hello World! Goodbye"
  "Hello World! Goodbye World!"
*/
const subscribe = example.subscribe(val => console.log(val));
Example 3: startWith multiple values

( jsBin | jsFiddle )

//emit values in sequence every 1s
const source = Rx.Observable.interval(1000);
//start with -3, -2, -1
const example = source.startWith(-3, -2, -1);
//output: -3, -2, -1, 0, 1, 2....
const subscribe = example.subscribe(val => console.log(val));

Additional Resources


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

results matching ""

    No results matching ""