Evan Carroll
Evan Carroll

Reputation: 1

RX.JS equivalent of fromArray?

Rx.js seems to have an operator toArray. What takes something from an array and emits the elements of the array? For instance, if I do,

ajax('localhost/foo')

and that returns returns {foo: [1,2,3]}. How can I map that to something that emits 1, 2, and 3?

Upvotes: 1

Views: 284

Answers (2)

antoinestv
antoinestv

Reputation: 3306

You are looking for from which convert an iterable into an observable.

toArray is not what you are looking for: it buffers all the values of an observable and emit them once the observable is complete. See: http://reactivex.io/documentation/operators/to.html

In your case you already have an observable which is your ajax call. It's an observable itsel even if it returns only one value and then immediatly complete.

If you map the value produced by your observable (the response) to another observable with from, you will have an observable of observable (which is called an high order observable). See: https://netbasal.com/understanding-mergemap-and-switchmap-in-rxjs-13cf9c57c885

To have a simple observable of numbers you will need to also use a combinaison operators (merge, switch, concat). Any of it will do the work.

ajax$.pipe(
  concatMap(x => from(x.response.events)),
).subscribe(x => console.log("foo", x)) // 1, then 2, then 3

Upvotes: 2

Evan Carroll
Evan Carroll

Reputation: 1

I found found mergeMap() works, but I don't know if there is a better way,

ajax$.pipe(
  mergeMap( x => x.response.events )
).subscribe( x => console.log("foo", x) );

Upvotes: 1

Related Questions