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?
I think, the problem you are facing is due to the fact that subscriptions are asynchronous. It does not wait for the
subscribecalls 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:Note that the
scanoperator 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 thesubscribeof the outer function.Hope that helps!