izanagi_1995
izanagi_1995

Reputation: 94

Map Observable of Array using Observable

I try to find a way to get this scenario working :

const test = this.talks$.pipe(
  exhaustMap(talks =>
    talks.map(t => this.getPersonById(t.personId).pipe(map(p => newTalkWithPerson(t, p))))
  ),
);

Currently, this emits 2 observable, each one emitting my TalkWithPerson object. (Observable<Observable<TalkWithPerson>>)

I would like to have an Observable<TalkWithPerson[]> if possible.

I was thinking going the hard way with getting all the people and all the talks and use combineLatest with a project function to match the records but I don't want to load all the persons, it will cause to load a huge list...

Thank you for your help !

StackBlitz : https://stackblitz.com/edit/talks-person

Upvotes: 1

Views: 241

Answers (2)

ZahiC
ZahiC

Reputation: 14687

Try this:

const test = this.talks$.pipe(
    exhaustMap(talks =>
        from(talks)
            .pipe(
                mergeMap(t => this.getPersonById(t.personId).pipe(map(p => newTalkWithPerson(t, p)))),                  
                toArray())
            )
  ),
);
  • Import from as creation method import { from } from "rxjs";
  • Import toArray same as the 'map' pipeable operator

Upvotes: 2

SiddAjmera
SiddAjmera

Reputation: 39432

Use flatMap operator for this. flatMap will unwrap an Observable<Observable<TalkWithPerson[]>> into Observable<TalkWithPerson[]>

So try doing this:

const test = this.talks$.pipe(
  exhaustMap(talks =>
    talks.flatMap(t => this.getPersonById(t.personId).pipe(map(p => newTalkWithPerson(t, p))))
  ),
);

Upvotes: 0

Related Questions