1

I have an end point that returns a list of favorites, then when this list returns i get each of these favorites and send to another endpoint to get the specific information of each of these favorite:

    this.favoriteData = [];
    const observables = [];
    favoriteList.forEach(favorite => {
      observables.push(this.assetService.getAsset(favorite.symbol)
        .pipe(takeWhile((response: AssetModel) => response.id !== 0)));
    });
    merge(...observables)
      .subscribe(res => {
        this.favoriteData.push(res);
        this.showLoading = false;
      });

As you can see the getAsset() function calls an endpoint, and it is inside an forEach, and im saving each of these response inside an array and spread this array inside a merge function of RXJS, but when i subscribe to the merged observable and append the response to the array favoriteData, the subscribe function behavior is like, binding one by one of the response data:

i want a behavior that waits all the requests to complete and then get all of the responses in one stream, im trying to use the forkJoin operator but the tslint tells that is deprecated and to use map operator, and i dont know how to use it to do what i want

enter image description here

Gabriel Guedes
  • 481
  • 5
  • 15
  • https://stackoverflow.com/questions/52486786/forkjoin-is-deprecated-resultselector-is-deprecated-pipe-to-map-instead – Fan Cheung Oct 17 '19 at 13:48
  • Possible duplicate of [Making sure observables in for loop are all finished before executing other code](https://stackoverflow.com/questions/55686084/making-sure-observables-in-for-loop-are-all-finished-before-executing-other-code) – wentjun Oct 17 '19 at 15:34
  • Please share your forkJoin code – frido Oct 17 '19 at 16:34

2 Answers2

0

You could use a combineLatest instead, which waits for all observables to complete before emitting.

combineLatest(...observables)
  .subscribe(res => {
    this.favoriteData.push(res);
    this.showLoading = false;
  });
Reqven
  • 1,688
  • 1
  • 8
  • 13
0

You can use from to generate an Observable which emits each element of the base array one at a time. Then, using mergeMap and toArray, you emit all required data at the end:

const favoriteData$ = from(favoriteList).pipe(
  mergeMap(favorite => this.assetService.getAsset(favorite.symbol)
    .pipe(takeWhile((response: AssetModel) => response.id !== 0))),
  toArray()
);
Will Alexander
  • 3,425
  • 1
  • 10
  • 17