defaultIfEmpty

signature: defaultIfEmpty(defaultValue: any): Observable

Emit given value if nothing is emitted before completion.

defaultIfEmpty - 图1

Examples

Example 1: Default for empty value

( jsBin |
jsFiddle )

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

( jsBin |
jsFiddle )

  1. import { defaultIfEmpty } from 'rxjs/operators';
  2. import { empty } from 'rxjs/observable/empty';
  3. //empty observable
  4. const empty = empty();
  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));

Additional Resources


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