Return an empty Observable Return an empty Observable typescript typescript

Return an empty Observable


For typescript you can specify generic param of your empty observable like this:

import 'rxjs/add/observable/empty' Observable.empty<Response>();


With the new syntax of RxJS 5.5+, this becomes as the following:

// RxJS 6import { EMPTY, empty, of } from "rxjs";// rxjs 5.5+ (<6)import { empty } from "rxjs/observable/empty";import { of } from "rxjs/observable/of";empty(); // deprecated use EMPTYEMPTY;of({});

Just one thing to keep in mind, EMPTY completes the observable, so it won't trigger next in your stream, but only completes. So if you have, for instance, tap, they might not get trigger as you wish (see an example below).

Whereas of({}) creates an Observable and emits next with a value of {} and then it completes the Observable.

E.g.:

EMPTY.pipe(    tap(() => console.warn("i will not reach here, as i am complete"))).subscribe();of({}).pipe(    tap(() => console.warn("i will reach here and complete"))).subscribe();


RxJS6 (without compatibility package installed)

There's now an EMPTY constant and an empty function.

  import { Observable, empty, EMPTY, of } from 'rxjs';  //This is now deprecated  var delay = empty().pipe(delay(1000));       var delay2 = EMPTY.pipe(delay(1000));

Observable.empty() doesn't exist anymore.