I believe the following code can be refactored using a flatMap but I cant seem to get it working as desired.
I understand flatMap essentially maps and then flattens, which is perfect for me as I'm using forkJoin so get an array of responses back from getAutocompleteSuggestions().
I want a single array of results upon subscription (which is what the code below produces), but changing the top level map to flatMap sends multiple single objects to the subscription. How can this code be better written with flatMap()?
const $resultsObservable: Observable<any> = Observable.of(query)
.switchMap(q => this.getAutocompleteSuggestions(q))
//tried changing the below to flatMap()
.map(res => {
return res.map(resp => {
const content = resp.content;
content.map(result => this.someMethod(result));
return content;
})
.reduce((flatArr, subArray) => flatArr.concat(subArray), []);
});
getAutocompleteSuggestions(query: string): Observable<any> {
const subs$ = [];
//... add some observables to $subs
return Observable.forkJoin(...subs$);
}