I am trying to create a simple redux-observable epic which debounces and is cancelable. My code:
export const apiValidate = action$ => {
return action$.ofType(validateRequestAction)
.debounceTime(250)
.switchMap((action) => (
Observable.ajax({
url: url,
method: 'GET',
crossDomain: true,
headers: {
"Content-Type": 'application/json'
},
responseType: 'json'
})
.map(payload => (new APISuccessValidate()))
.takeUntil(action$.ofType(validateCancelAction))
.catch(payload => ([new APIFailureValidate()]))
));
};
The code only works sometimes. Depending on the speed of the response from the server, I believe 1 of 2 scenarios can occur.
Scenario 1 (works):
Time 0ms - Fire validateRequestAction
Time 250ms - Ajax request occurs
Time 251ms - Fire validateCancelAction
Time 501ms - validateCancelAction passes debounce and cancels properly
Nothing else occurs
Scenario 2 (broken)
Time 0ms - Fire validateRequestAction
Time 250ms - Ajax request occurs
Time 251ms - Fire validateCancelAction
Time 400ms - Ajax returns, APISuccessValidate action fired
Time 501ms - validateCancelAction passes debounce and there is nothing to cancel
Is there a way I can write my epic such that only the validateCancelAction can bypass the debounceTime and cancel the ajax call without waiting?
Thanks!