Learn RxJS
Search…
defaultIfEmpty

signature: defaultIfEmpty(defaultValue: any): Observable

Emit given value if nothing is emitted before completion.

Examples

Example 1: Default for empty value
1
// RxJS v6+
2
import { defaultIfEmpty } from 'rxjs/operators';
3
import { of } from 'rxjs';
4
5
//emit 'Observable.of() Empty!' when empty, else any values from source
6
const exampleOne = of().pipe(defaultIfEmpty('Observable.of() Empty!'));
7
//output: 'Observable.of() Empty!'
8
const subscribe = exampleOne.subscribe(val => console.log(val));
Copied!
Example 2: Default for Observable.empty
1
// RxJS v6+
2
import { defaultIfEmpty } from 'rxjs/operators';
3
import { empty } from 'rxjs';
4
5
//emit 'Observable.empty()!' when empty, else any values from source
6
const example = empty().pipe(defaultIfEmpty('Observable.empty()!'));
7
//output: 'Observable.empty()!'
8
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 2yr ago