💡 A BehaviorSubject can also start with an initial value!
The startWith
operator is a great tool when you need to provide an initial value to an observable sequence, ensuring that the consumer always receives a value upon subscription. It's a handy way to set a default state or value for your observables, making it easier for subscribers to handle the data and minimizing the chances of encountering unexpected scenarios.
A real-world example can be seen in a search functionality, where the search results should display a list of popular items as a default state before the user starts typing their query. By using startWith, you can seamlessly provide this default data to your subscribers.
Keep in mind that startWith emits the initial value immediately upon subscription. This behavior is helpful when you want to make sure your subscribers receive a value right away, even before the source observable starts emitting values.
( example tests )
( 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 0
const example = source.pipe(startWith(0));
//output: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));
( 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 previous
const 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));
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { startWith } from 'rxjs/operators';
import { interval } from 'rxjs';
//emit values in sequence every 1s
const source = interval(1000);
//start with -3, -2, -1
const example = source.pipe(startWith(-3, -2, -1));
//output: -3, -2, -1, 0, 1, 2....
const subscribe = example.subscribe(val => console.log(val));
- Alphabet Invasion Game
- Breakout Game
- Car Racing Game
- Platform Jumper Game
- Smart Counter
- Space Invaders Game
- Stop Watch
- Tank Battle Game
- Tetris Game
- Uncover Image Game
- 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