I currently have a service where i fetch some templates with help of expand to display them in the view. The idea is to keep fetching untill i have everything.
However, when i pipe the expand it replaces the values instead of adding them, how do i solve this?
Example:
templates$: Observable<Template[]>;
let count = 0;
this.templates$ = this.templateService.getTemplates(0, 5).pipe(
expand(result => {
count = result.length;
if (result.length === 5) {
return this.templateService.getTemplates(count, 5);
} else {
return empty();
}
})
);
CodePudding user response:
expand
does not replace value, it rather emits each time you receive the templates in groups of five. In your view, if you use template$ | async
, you'll only see the last result.
To collect all templates, you can use scan
operator.
templates$: Observable<Template[]>;
let count = 0;
this.templates$ = this.templateService.getTemplates(0, 5).pipe(
expand(result => {
count = result.length;
if (result.length === 5) {
return this.templateService.getTemplates(count, 5);
} else {
return empty();
}
}),
scan((acc, curr) => acc.concat(curr))
);
You could also use reduce
operator the same way, if you don't want to show intermediate results.