How can I set observables based off a condition in a for loop and return them as one

97 Views Asked by At

I need to loop through a list of id's, checking each for an if condition and then based on the result of that if condition, get an observable from a method. I need to list the returned observables together after for a subscribe method.

I've added some pseudocode below:

list results;

for(i < 10) {
    if(i === xyz)
        results[i] = get obseravable-type-1
    else
        results[i] = get obseravable-type-1
}

return results;

The problem is that this either ignores the calls and returns an empty list before the subscribe finishes, or returns an array of observables.

How would I go about doing this?

1

There are 1 best solutions below

0
enniokerber On

I think, the problem you are facing is due to the fact that subscriptions are asynchronous. It does not wait for the subscribe calls to be finished. I recommend you to return an Observable from the method you posted and then subscribe to that observable from the outside to retrieve a list of results. I advise you to use some RxJS operators to solve this. For example:

import {from, Observable, scan, switchMap} from "rxjs";

function loopOverIds(): Observable<SomeResultType[]> {
  const ids = [1, 2, 3];
  return from(ids).pipe(
    switchMap((id: number) => checkCondition(id) ? getObservable1() : getObservable2()),
    scan((resultList: SomeResultType[], resultFromPreviousObservable: SomeResultType) => {
      resultList.push(resultFromPreviousObservable);
      return resultList;
    }, [])
  );
}

function outerFunction() {
  loopOverIds()
    .subscribe(resultList => /* Do something with the result list */)
}

Note that the scan operator works as an accumulator here. It will collect the results of all previous observables into an array and when finished with all ids it will finally execute the callback function within the subscribe of the outer function.

Hope that helps!