Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS Observable Transform Array To Multiple Values

Tags:

angular

rxjs

I'm making an Angular 2 HTTP get request and in return I get Observable<Message[]> I want to transform this observable into multiple emit. So let's say the server returned Message array with length 3. I would like to get 3 notification in my subscribe call (on for each value in the array) instead of getting one call with the array.

e.g : ['Hello','Hey','Howdy'] - > 'Hello', 'Hey','Howdy'

I found an operator that does transform the array (Observable.for), but this operator takes as an argument an array and not an Observable.

like image 985
MasterOfPuppets Avatar asked Jun 13 '17 06:06

MasterOfPuppets


People also ask

Can Observable return multiple values?

Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time). Observables not only able to return a value synchronously, but also asynchronously.

What is switchMap in RxJS?

RxJS switchMap() operator is a transformation operator that applies a project function on each source value of an Observable, which is later merged in the output Observable, and the value given is the most recent projected Observable.

What is map operator in RxJS?

RxJS map() operator is a transformation operator used to transform the items emitted by an Observable by applying a function to each item. It applies a given project function to each value emitted by the source Observable and then emits the resulting values as an Observable.


2 Answers

You can use the concatAll operator to flatten the array (mergeAll will work as well).

Observable.of(['Hello','Hey','Howdy'])
  .concatAll()
  .subscribe(console.log)

See demo: https://jsbin.com/gaxajex/3/edit?js,console

like image 119
martin Avatar answered Oct 18 '22 04:10

martin


Try this:

Observable.from(yourRequest())
    .flatMap(msgList => Observable.from(msgList))
    .subscribe(msg => console.log(msg));

yourRequest() in this case should return array.

If yourRequest() returns Observable then:

yourRequest().flatMap(msgList => Observable.from(msgList))
    .subscribe()
like image 33
SasaT Avatar answered Oct 18 '22 03:10

SasaT