Learn RxJS
Search…
startWith

signature: startWith(an: Values): Observable

Emit given value first.

πŸ’‘ A BehaviorSubject can also start with an initial value!
​​
​
​

Examples

Example 1: startWith on number sequence
1
// RxJS v6+
2
import { startWith } from 'rxjs/operators';
3
import { of } from 'rxjs';
4
​
5
//emit (1,2,3)
6
const source = of(1, 2, 3);
7
//start with 0
8
const example = source.pipe(startWith(0));
9
//output: 0,1,2,3
10
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: startWith for initial scan value
1
// RxJS v6+
2
import { startWith, scan } from 'rxjs/operators';
3
import { of } from 'rxjs';
4
​
5
//emit ('World!', 'Goodbye', 'World!')
6
const source = of('World!', 'Goodbye', 'World!');
7
//start with 'Hello', concat current string to previous
8
const example = source.pipe(
9
startWith('Hello'),
10
scan((acc, curr) => `${acc} ${curr}`)
11
);
12
/*
13
output:
14
"Hello"
15
"Hello World!"
16
"Hello World! Goodbye"
17
"Hello World! Goodbye World!"
18
*/
19
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 3: startWith multiple values
1
// RxJS v6+
2
import { startWith } from 'rxjs/operators';
3
import { interval } from 'rxjs';
4
​
5
//emit values in sequence every 1s
6
const source = interval(1000);
7
//start with -3, -2, -1
8
const example = source.pipe(startWith(-3, -2, -1));
9
//output: -3, -2, -1, 0, 1, 2....
10
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 2yr ago