Search code examples
rxjsobservablereactive-extensions-js

Augment seperate values in observable of array - RxJS


I've been trying to tackle this problem for a while now, I would guess this is a pretty common problem but what I want to do is augment items in an array coming from an observable, and the augmentation happens with an observable or promiselike So I want something like the following:

function augment(person: Person): Observable<PersonWithAddress> { 
    // does ajax call or something
}

const items$: Observable<Person[]>;

items$
    .do(x => {}) // x would be of type Person[]
    .flatFlatMap(person => { // person would be of type Person
        return augment(person); // this would return an Observable<PersonWithAddress>
    })
    .subscribe(peopleWithAddresses => { // peopleWithAddresses would be of type PersonWithAddress[]
    })

Is there some kind of operator for this, I get I can augment or map a single item emitted from an observable to something else coming from an observable with flatMap, but is there something like flatFlatMap or so.


Solution

  • You can use forkJoin to do what you want.

    It takes an array of observables (or promises) and, when all have completed (or resolved), it emits an array containing the last emitted (or resolved) values:

    import { Observable } from "rxjs/Observable";
    import "rxjs/add/observable/forkJoin";
    
    
    items$
      .flatMap((people: Person[]) => Observable.forkJoin(
        people.map(person => augment(person))
      ))
      .subscribe((peopleWithAddresses: PersonWithAddress[]) => {
        // ...
      });