Answer the question
In order to leave comments, you need to log in
How to use SwitchMap RxJs for non "Observable" features and cancel previous request?
After reading a lot of documentation, I still did not understand the SwitchMap operator.
I need to cancel the request if it hasn't been completed yet.
But not everything is as simple as on the forums.
The user selects product categories and they are loaded. If a person "clicks" often, then previous requests should not be considered.
But I'm using fetchApi, not the standard angularHttpClient, and there is a question of canceling previous requests through this option.
I have wrapper functions that return a promise. How to tie it up so that previous requests are reset (I'm not for fetchCancell, but just at least to take the latest result of the request (because in fact the previous request can sometimes be completed faster - I need to chop previous requests))
async selectCategory(id) {
data = await myFuncGetDataFromServer(id){}
}
Answer the question
In order to leave comments, you need to log in
switchMap does not cancel any requests. It unsubscribes from the stream.
And already HttpClient is so arranged that it cancels the request when unsubscribing. Those. calls XMLHttpRequest.abort() when the TearDown logic fires.
If you are using fetch rather than xhr, then you can also wrap it in an observable. Something like this
function request(url) {
return new Observable(observer => {
const controller = new AbortController()
const signal = controller.signal
signal.addEventListener("abort", () => observer.complete());
fetch(url, { signal })
.then(res => {
observer.next(res);
observer.complete();
})
.catch((err) => {
observer.error(err);
observer.complete();
});
return () => controller.abort();
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question