Skip to content

Latest commit

 

History

History
55 lines (39 loc) · 1.77 KB

defaultifempty.md

File metadata and controls

55 lines (39 loc) · 1.77 KB

defaultIfEmpty

signature: defaultIfEmpty(defaultValue: any): Observable

Emit given value if nothing is emitted before completion.

Ultimate RxJS

Examples

Example 1: Default for empty value

( Stackblitz | jsBin | jsFiddle )

// RxJS v6+
import { defaultIfEmpty } from 'rxjs/operators';
import { of } from 'rxjs';

//emit 'Observable.of() Empty!' when empty, else any values from source
const exampleOne = of().pipe(defaultIfEmpty('Observable.of() Empty!'));
//output: 'Observable.of() Empty!'
const subscribe = exampleOne.subscribe(val => console.log(val));
Example 2: Default for Observable.empty

( Stackblitz | jsBin | jsFiddle )

// RxJS v6+
import { defaultIfEmpty } from 'rxjs/operators';
import { empty } from 'rxjs';

//emit 'Observable.empty()!' when empty, else any values from source
const example = empty().pipe(defaultIfEmpty('Observable.empty()!'));
//output: 'Observable.empty()!'
const subscribe = example.subscribe(val => console.log(val));

Additional Resources


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/defaultIfEmpty.ts