Use RxJS Async Requests and Responses

Share this video with your friends

Send Tweet

In this lesson we start building a small UI widget: suggestions box displaying users to follow in Github. We will learn how to perform network requests to a backend using RxJS Observables.

jvcjunior
jvcjunior
~ 8 years ago

Could this part of the code: var responseStream = requestStream .flatMap(requestUrl => Rx.Observable.fromPromise(jQuery.getJSON(requestUrl)) );

be replaced by: var responseStream = Rx.Observable.fromPromise(jQuery.getJSON('https://api.github.com/users'));

?

André Staltz
André Staltz(instructor)
~ 8 years ago

Hi jvcjunior. It would probably behave the same, but it's still different because the requestStream may emit many URLs over time, not just one hard-coded URL.

Rafael Bitencourt
Rafael Bitencourt
~ 8 years ago

I'm leaving here an example of this using RxJS v5.0.0-beta.10

import Rx from 'rxjs/Rx';
import fetch from 'fetch-jsonp';

const fetchEndpoint = url => fetch(url)
	.then(response => response.json())
	.then(response => response.data);

const request$ = Rx.Observable.of('https://api.github.com/users');
const response$ = request$
	.flatMap(url => Rx.Observable.fromPromise(fetchEndpoint(url)));

response$.subscribe((response) => console.log(response));

Please let me know if you see a problem with this implementation.

Kostiantyn Hryshyn
Kostiantyn Hryshyn
~ 8 years ago

How can I combine interval & request to the server with Observable? Could someone provide a hint?

André Staltz
André Staltz(instructor)
~ 8 years ago

Hi Kostiantyn, you could accomplish that with another flatMap or with combineLatest. Here is how you could do it with flatMap (or a variant like switchMap/flatMapLatest):

var responseStream = Rx.Observable.interval(1000)
  .switchMap(i => requestStream)
  .switchMap(requestUrl => Rx.Observable.fromPromise($.getJSON(requestUrl)))

(switchMap is from RxJS v5. flatMap and flatMapLatest are from RxJS v4)

Mike
Mike
~ 7 years ago

Very well explained.