I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve.
Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has enough data, obtained through subscribe calls, I would like to stop the process and return the complete array.
// Just to give you some context, there's a class variable named 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 follow the same logic as above. */
}
);
}
I understand that nesting subscribes is not recommended, but this gives you an idea of my requirements. I've looked at takeWhile, which works based on a condition, but I haven't figured out how to make additional calls if that condition fails. Does anyone have suggestions for an operator that fits this use case?
Thank you!
- obsFunctionThatGetsMeData returns Observable
Update: Found a solution by 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);
}
}
}));
}