Return an empty Observable

Murhaf Sousli picture Murhaf Sousli · Jul 24, 2016 · Viewed 157k times · Source

The function more() is supposed to return an Observable from a get request

export class Collection{

    public more = (): Observable<Response> => {
       if (this.hasMore()) {

         return this.fetch();
       }
       else{
         // return empty observable
       }
    }

    private fetch = (): Observable<Response> => {
       return this.http.get('some-url').map(
          (res) => {
              return res.json();
          }
       );
    }
}

In this case I can only do a request if hasMore() is true, else I get an error on subscribe() function subscribe is not defined, how can I return an empty observable?

this.collection.more().subscribe(
   (res) =>{
       console.log(res);
   },
   (err) =>{
       console.log(err);
   }
)

Update

In RXJS 6

import { EMPTY } from 'rxjs'

return EMPTY; 

Answer

Andrei Petrov picture Andrei Petrov · Aug 19, 2016

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

import 'rxjs/add/observable/empty' 

Observable.empty<Response>();