Learn RxJS
Search…
empty

signature: empty(scheduler: Scheduler): Observable

Observable that immediately completes.

Examples

Example 1: empty immediately completes
1
// RxJS v6+
2
import { empty } from 'rxjs';
3
4
//output: 'Complete!'
5
const subscribe = empty().subscribe({
6
next: () => console.log('Next'),
7
complete: () => console.log('Complete!')
8
});
Copied!
Example 2: empty with timer
1
// RxJS v6+
2
import { interval, fromEvent, merge, empty } from 'rxjs';
3
import { switchMap, scan, takeWhile, startWith, mapTo } from 'rxjs/operators';
4
5
const countdownSeconds = 10;
6
const setHTML = id => val => (document.getElementById(id).innerHTML = val);
7
const pauseButton = document.getElementById('pause');
8
const resumeButton = document.getElementById('resume');
9
const interval$ = interval(1000).pipe(mapTo(-1));
10
11
const pause$ = fromEvent(pauseButton, 'click').pipe(mapTo(false));
12
const resume$ = fromEvent(resumeButton, 'click').pipe(mapTo(true));
13
14
const timer$ = merge(pause$, resume$)
15
.pipe(
16
startWith(true),
17
// if timer is paused return empty observable
18
switchMap(val => (val ? interval$ : empty())),
19
scan((acc, curr) => (curr ? curr + acc : acc), countdownSeconds),
20
takeWhile(v => v >= 0)
21
)
22
.subscribe(setHTML('remaining'));
Copied!

Additional Resources

Last modified 1yr ago