R
R
Roman Rakzin2022-02-21 12:53:00
Angular
Roman Rakzin, 2022-02-21 12:53:00

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){}
}

How can I make a similar request with SwitchMap ? Or through not RxJs, but what would the previous ones be canceled? (it would be better of course on Rxjs)

Thanks.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2022-02-22
@Xuxicheta

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();
  });
}

I wrote from memory, maybe it even works :)
When creating an Observable, the callback passed to it returns the logic that will be executed when unsubscribing from it, i.e. tear down

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question