rxjs defaultifempty for observable<void> in typescript

You can use the defaultIfEmpty operator with Observable<void> in the following way:

index.ts
import { of } from 'rxjs';
import { defaultIfEmpty } from 'rxjs/operators';

const observable$ = of<void>().pipe(
  defaultIfEmpty(null)
);

observable$.subscribe((val) => {
  if (val === null) {
    console.log('Observable is empty!');
  }
});
245 chars
13 lines

In the code above, of function creates an observable that emits a single value of void type. Then we apply the defaultIfEmpty operator to the observable which emits a null value if the observable is empty. Finally, we subscribe to the observable and check whether the emitted value is null or not. If it is null, then it means that the observable is empty.

gistlibby LogSnag