RxJS - Nuggets of wisdom
Valerio
Posted on June 30, 2020
Do you know "defaultIfEmpty" operator?
It emits the default value if the source completes without having emitted any value.
It could be helpful in several scenarios.
import { of } from 'rxjs';
import { map, defaultIfEmpty } from 'rxjs/operators';
// source2 doesn't have any values; using defaultIfEmpty, we can have a "default" value.
const source1 = of().pipe(
defaultIfEmpty('Hello There')
);
source1.subscribe(x => console.log(x));
// source1 has a value
const source2 = of('Hello World').pipe(
defaultIfEmpty('Hello There')
);
source2.subscribe(x => console.log(x));
Live Code
💖 💪 🙅 🚩
Valerio
Posted on June 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.