I need to execute observables created from array. The condition is next observable should wait until previous observable has been completed. Thanks in advance :-).
export class AppComponent{
arr: number[] = [5, 4, 1, 2, 3];
fetchWithObs() {
from(this.arr)
.pipe(
map((value) => {
return this.getData(value);
})
)
.subscribe((data) => {
console.log(data);
/**
* The expoected output should be
* 5 completed
* 4 completed
* 1 completed
* 2 completed
* 3 completed
*/
});
}
getData(p: number) {
return new Observable<string>((s) => {
setTimeout(() => {
s.next(`${p} completed`);
s.complete();
}, p * 1000);
});
}
}
CodePudding user response:
Try concatMap
.
export class AppComponent{
arr: number[] = [5, 4, 1, 2, 3];
fetchWithObs() {
from(this.arr)
.pipe(
concatMap(this.getData)
)
.subscribe(console.log);
}
getData(p: number) {
return new Observable<string>((s) => {
setTimeout(() => {
s.next(`${p} completed`);
s.complete();
}, p * 1000);
});
}
}
Stackblitz: https://stackblitz.com/edit/typescript-axx8gf?file=index.ts