I research Rxjs with exhaustMap but it is higher-order observable. My case just simple add a row to db. is there any other way since i don't use higher-order
CodePudding user response:
The higher order operator exhaustMap
will ignore any emitted values from source until inner observable completes.
https://www.learnrxjs.io/learn-rxjs/operators/transformation/exhaustmap
In your case you can do such:
const btnClicks$ = fromEvent(addRowBtn, 'click')
btnClicks$.pipe(
exhaustMap((_) => {
//clear form here for example to make sure the user will not send the same data again.
return callToApi(formData)
})
// Any click event will simply be ignored until you get a response from api.
).subscribe()
Take note here that exhaustMap
only works with observables, if your callToApi() function return a promise you can wrap it with defer() like so:
const btnClicks$ = fromEvent(addRowBtn, 'click')
const addRowApi = defer(() => callToApi(formData)) // this returns an observable that exhaustMap can subscribe to.
btnClicks$.pipe(
exhaustMap((_) => {
//clear form here for example to make sure the user will not send the same data again from example
return addRowApi()
})
// Any click event will simply be ignored until you get a response from api.
).subscribe()
CodePudding user response:
Sounds like you're after throttleTime
.
throttleTime
emits a value from the source Observable, then ignores subsequent source values for duration milliseconds, then repeats this process.
Here's an example:
const clicks$ = fromEvent(startBtn, 'click');
function dataBaseApi(dataRow): Observable<ResponseType>{
return addDataToRow(dbClient, dataRow);
}
clicks$.pipe(
throttleTime(2000),
map(clickToData),
concatMap(dataBaseApi)
).subscribe();