DEV Community

loading...

RxJS - Nuggets of wisdom

valeriopisapia profile image Valerio ・1 min read

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

Discussion (0)

pic
Editor guide