💡 A BehaviorSubject can also start with an initial value!
( example tests )
Example 1: startWith on number sequence
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { startWith } from 'rxjs/operators';import { of } from 'rxjs';//emit (1,2,3)const source = of(1, 2, 3);//start with 0const example = source.pipe(startWith(0));//output: 0,1,2,3const subscribe = example.subscribe(val => console.log(val));
Example 2: startWith for initial scan value
( StackBlitz | | jsBin | jsFiddle )
// RxJS v6+import { startWith, scan } from 'rxjs/operators';import { of } from 'rxjs';//emit ('World!', 'Goodbye', 'World!')const source = of('World!', 'Goodbye', 'World!');//start with 'Hello', concat current string to previousconst example = source.pipe(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
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { startWith } from 'rxjs/operators';import { interval } from 'rxjs';//emit values in sequence every 1sconst source = interval(1000);//start with -3, -2, -1const example = source.pipe(startWith(-3, -2, -1));//output: -3, -2, -1, 0, 1, 2....const subscribe = example.subscribe(val => console.log(val));
startWith 📰 - Official docs
Displaying initial data with startWith
🎥 💵 - John Linquist
Clear data while loading with startWith
🎥 💵 - André Staltz
Combination operator: concat, startWith
🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/startWith.ts