A
A
Artem Ryzhov2020-01-18 11:56:07
Angular
Artem Ryzhov, 2020-01-18 11:56:07

How to show loader for slow request using RxJs?

Can you please tell me how to properly delay the display of the loader using RxJs and Angular? The point is to show the loader only if the requests are slow and avoid showing it for a fraction of a second.
- send a request
- if the request lasts more than 500 ms, then show the loader
- when the response comes from the server, hide the loader, return the response
- if the response from the server comes earlier, then immediately return the response, do not show the
loader - if the loader is already shown, then display it for at least 300ms
Example 1:
0ms: send a request
100ms: receive a response 100ms: send a
response
Example 2:
0ms: send a request
500ms: show a loader
1000ms: receive a response
1000ms: hide loader, return response
Example 3:
0ms: send request
500ms: show loader, minimum
300ms 550ms: receive response
800ms: hide loader, return response

async showUser(id: number) {
  this.showLoader = false;
  const data = from(this.usersService.findOne(id)); // Objervabe from Promise
  // ... что дальше?
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-01-18
@ryzhovas

https://stackblitz.com/edit/angular-ws6pee
delays increased to 1000 and 2500 for clarity
In the case of multiple downloads, collisions are possible, it will be necessary to refine.
Loader, debouncer and timeouts can and should be isolated in a separate component (or directive), which will receive the current value of the loader (here it is setLoader) as an input parameter.
In principle, in general, you can even make a pipe.
- if the request lasts more than 500 ms, then show the loader
- if the loader is already shown, then display it for at least 300 ms
If these two numbers were the same, it would be possible to get by with one debounceTime on the loader.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question