Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  105] [ 7]  / answers: 1 / hits: 135286  / 9 Years ago, mon, november 2, 2015, 12:00:00

I am starting to use RxJS and I don't understand why in this example we need to use a function like flatMap or concatAll; where is the array of arrays here?



var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseMetastream = requestStream
.flatMap(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});

responseMetastream.subscribe(url => {console.log(url)})


If someone can visually explain what is happening, it will be very helpful.


More From » rxjs

 Answers
11

When I started to have a look at Rxjs I also stumbled on that stone. What helped me is the following:




  • documentation from reactivex.io . For instance, for flatMap: http://reactivex.io/documentation/operators/flatmap.html

  • documentation from rxmarbles : http://rxmarbles.com/. You will not find flatMap there, you must look at mergeMap instead (another name).

  • the introduction to Rx that you have been missing: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. It addresses a very similar example. In particular it addresses the fact that a promise is akin to an observable emitting only one value.

  • finally looking at the type information from RxJava. Javascript not being typed does not help here. Basically if Observable<T> denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable<T> as its argument, and returns Observable<T>. map takes a function of type T' -> T and returns Observable<T>.



    Going back to your example, you have a function which produces promises from an url string. So T' : string, and T : promise. And from what we said before promise : Observable<T''>, so T : Observable<T''>, with T'' : html. If you put that promise producing function in map, you get Observable<Observable<T''>> when what you want is Observable<T''>: you want the observable to emit the html values. flatMap is called like that because it flattens (removes an observable layer) the result from map. Depending on your background, this might be chinese to you, but everything became crystal clear to me with typing info and the drawing from here: http://reactivex.io/documentation/operators/flatmap.html.



[#64538] Thursday, October 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;