I am new to rxjs and can't seem to find the correct operator for what I am trying to do.
In my example, I have an array I need to populate with results from an another observable, and once I have enough results in that array from making subscribe calls, I want to break and return the array.
// for reference, there is a class variable called keys
result = getResults(data, index).subscribe((result: any[]) => {
doSomethingWith(result);
});
getResults(data: any[], index: number) : Observable<any[]> {
obsFunctionThatGetsMeData(keys[index]).subscribe(result =>
data = data.concat(result);
if(data.length >= NEEDED_NUM_DATA) {
return Observable.of(data);
} else {
/* need to call obsFunctionThatGetsMeData(keys[index++]) and do the same logic as above. */
}
);
}
I know it is bad practice to put a subscribe in a subscribe, this is just the idea of what I'm looking for. I know takeWhile works on a condition, but I don't see how I can make extra calls if that condition fails. Does anyone know what operator is best for this kind of behavior?
Thanks!
- obsFunctionThatGetsMeData returns Observable
Solved my own question Using recursion & switchmap
getResults(data: any[], index: number): Observable<any> {
return obsFunctionThatGetsMeData(keys[index]).pipe(
switchMap(result => {
if (result) {
data= data.concat(result);
if (data.length < NEEDED_NUM_DATA && index < keys.length) {
return getResults(data, ++index);
} else {
return Observable.of(data);
}
}
}));
}
getResults
, a single value. InobsFunciton...
you repeat the same pattern of using single value. I do see the comment[index++]
– Randy CasburnNEEDED_NUM_DATA
in advance. Please check my answer below. It uses promises because they are the correct tool to use here. – Randy Casburn