0

How can I delay an http request only if it completes under 1second.

first scenario: - http request completes in 300ms, then we wait until 1 second ends.

second scenario: - http request completes in 1 second and 300ms, then we DO NOT delay.

how to accomplish this with observables ?

3
  • Do you mind asking what is the scenario for calling an API and delaying it? While the answer below works, I am curious... Commented Oct 17, 2017 at 1:18
  • @IgorSoloydenko We had a problem with an http request that was sometimes faster than our loading animation and it wasn't pretty so we all agreed that waiting for the animation to finish was ok, having results from the http call as soon as possible wasn't highly important. Commented Oct 17, 2017 at 10:34
  • Ahhhh, so that was a UX issue basically. Makes sense! Commented Oct 17, 2017 at 11:03

1 Answer 1

6

You can use forkJoin to wait until both Observables complete:

Observable.forkJoin(
  this.http.get(...),
  Observable.of(null).delay(1000),
  r => r // Use only the HTTP response
))
.subscribe();
Sign up to request clarification or add additional context in comments.

1 Comment

Here's a Plunkr with a function that you might reuse @Rachid Oussanaa. I've also added a little benchmark to show the result with a fast (300ms) and a slow (1300ms) response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.