I would like to concat dynamically observables. Start the first observable and maybe queue another observable and it will start after the first one finishes (could be one or more observables). I don't know the way to do this.
This is my method who start the observable:
saveConditional(data: any) {
console.log(data);
this._documentService
.createVariable(data, this.documentId)
.subscribe((x: any) => {
console.log(x.data.variables);
});
}
I call this method by: this.saveConditional(dataToSend);
dataToSend
contains parameters to save in DB and it's an object.
createVariable
return the data from DB updated (with the new registry)
The problem is when I try to start this method multiple times. It just create the last call sent (every call for this method is a register in DB and I need to do multiples registers).
I was looking for merge
pipe, but I don't how to implement it dynamically.
note: **async/await is not an option.
CodePudding user response:
If you want to update multiple items in the database, below snippet could help you with this.
It creates an array of Observables, merges them and then subscribes. This will execute them all at once(!). If it should be in order then use concat in stead of merge.
saveConditional(data: any[]) {
console.log(data);
let obsArray$: Observable[] = [];
data.forEach((dataItem)=>{
obsArray$.push(this._documentService
.createVariable(dataItem, this.documentId));
}
merge(obsArray$).((x: any) => {
console.log(x.data.variables);
});
}
CodePudding user response:
You can use concat(https://www.learnrxjs.io/learn-rxjs/operators/combination/concat) operator for this type of situation.
concat(saveConditional(data1), saveConditional(data2), saveConditional(data3), ...).subscribe(console.log);
After the first saveConditional(data1) request is completed (observable completion and not the value emition!), this will run the second request (saveConditional(data2)) and the the third one, etc..
CodePudding user response:
You can use concatMap. It puts all the transactions you sent in queue and starts to process in order. https://stackblitz.com/edit/typescript-pkyxa1?devtoolsheight=100&file=index.ts