How to convert a Fetch API response to RxJS Observable?

wonderful world picture wonderful world · Jul 3, 2017 · Viewed 14.5k times · Source

How can I convert whatever Fetch API returns to RxJS Observable? Does RxJS.fromPromise help?

Answer

wawka picture wawka · Nov 1, 2017

As fetch call returns yet another promise containing the response object, I'd go with creating your own observable:

import { Observable } from 'rxjs';

const data$ = Observable.create(observer => {
  fetch('http://server.com')
    .then(response => response.json()) // or text() or blob() etc.
    .then(data => {
      observer.next(data);
      observer.complete();
    })
    .catch(err => observer.error(err));
});

data$.subscribe(data => /*do something with data*/);