Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine mergeMap observables calls and return just one value for the whole observable

I have this scenario in typescript/angular with rxjs 6.5:

   main(){

        const properties = ['session', 'user'];
        const source: Observable<any> = from(properties);

        source
            .pipe(
                mergeMap(key => this.getKey().map((value) => ({key: key, value: value}))),
                tap((result) => {
                    // sending the result elsewhere;
                }),
            ).subscribe(
            (result) => {
                console.log('Final result ->', result);
            }
        );

        console.log('\n');

    }

    getKey(): Observable<any> {
        // Mock function that returns an observable that emits 1 value
        const observable = from(['test']);

        return observable;
    }

The output is:

Final result -> {key: "session", value: "test"}
Final result -> {key: "user", value: "test"}

1st question: How do I return, in the most elegant way, upon subscription on source, just 1 value, with the combined results of the inner observables?

My wanted output, with the subscription in this way (because I want this combined operation to be in the pipe), would be:

(...).subscribe(
(result) => {console.log('Final Result:', result}
)

OUTPUT:

Final result -> [{key: "session", value: "test"}, {key: "user", value: "test"}]

2nd question If I don't care about the result of the inner observables, how do I return just 1 value or how do I know when all the inner observables have been completed?

Thanks in advance.

like image 306
Martin Avatar asked Apr 30 '19 00:04

Martin


1 Answers

To get combined result of all response of mergeMap, you can also try like this:

return this.request1().pipe(
  mergeMap(res1=> this.request2(res1.id).pipe(
    map(res2=> {
      return {
        res1: res1,
        res2: res2
      }
    })
  ))
)
like image 70
Adrita Sharma Avatar answered Oct 17 '22 22:10

Adrita Sharma