( Stackblitz | jsBin | jsFiddle )
// RxJS v6+
import { defaultIfEmpty } from 'rxjs/operators';
import { of } from 'rxjs';
// 当源 observable 为空时,发出 'Observable.of() Empty!',否则发出源的任意值
const exampleOne = of().pipe(defaultIfEmpty('Observable.of() Empty!'));
// 输出: 'Observable.of() Empty!'
const subscribe = exampleOne.subscribe(val => console.log(val));
( Stackblitz | jsBin | jsFiddle )
// RxJS v6+
import { defaultIfEmpty } from 'rxjs/operators';
import { empty } from 'rxjs';
// 当源 observable 为空时,发出 'Observable.empty()!',否则发出源的任意值
const example = empty().pipe(defaultIfEmpty('Observable.empty()!'));
// 输出: 'Observable.empty()!'
const subscribe = example.subscribe(val => console.log(val));
- defaultIfEmpty 📰 - 官方文档
📁 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/defaultIfEmpty.ts