Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RxJS setting minimum delay for a request

I want to show a loader when making requests in my app. But sometimes my server responds way too fast and the loader simply flashes for a split second causing an unpleasant experience.

In the past what I’ve always done is use combineLatest with a timer to create minimum request delay.

const request = getRequestPromise();
await lastValueFrom(combineLatest([request, timer(1000)]).pipe(mapRx(([x]) => x)))

What this does is if the server responds in less than one second, then just finish waiting 1 second before resolving. If however the server responds in 3 seconds, this code will not add an extra second.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This has been working great. But I just realized if the request fails (resulting in an exception) it does not respect the minimum delay. It resolves immediately and causes the unpleasant loader flash.

How can I have this work for both failed and succeeded requests?

I need to be able to still handle the success/error from the request itself:

await lastValueFrom(combineLatest([request, timer(1000)])     
  .pipe(mapRx(([x]) => x)))
  .then(() => console.log('handle successful request'))
  .catch(() => console.log('handle error'))

>Solution :

You can use materialize and dematerialize for this so that there will be no error from the first stream ever, and only once the combineLatest has been resolved and you return the value from the request, you dematerialize it so if there was an error, it throws as expected:

combineLatest([request.pipe(materialize()), timer(1000)]).pipe(
  map(([x]) => x),
  dematerialize()
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading