bob
bob

Reputation: 1097

Observable for http calls with certain action on each timeout

My strategy for http calls currently looks like this:
Timeout each request after 10s, and retry the call for max. 5 times.
As far as I can tell I somewhat figured this out, it seems to work:

this.httpClient.post(url, body)
  .timeout(10000)
  .retryWhen(error => {
    return error.delay(500).take(5);
  })
.subscribe(
  response => {
    // stuff
  },
  error => {
    // stuff
  }

Now my problem is that I'd need to do something when every timeout occurs (e.g. just print a short info text 'timeout 1', 'timeout 2'...).

How do I do this?

Currently at rxjs 5.4.2 with Angular 4.2.4 (shouldn't matter, I guess).

Upvotes: 1

Views: 443

Answers (2)

martin
martin

Reputation: 96899

The timeout operator emits an error notification so if you want to be able to perform a side-effect you can use do.

Be aware that do takes three arguments for next, error and complete notification respectively so the correct way to use it for you is like this:

this.httpClient.post(url, body)
  .timeout(10000)
  .do(null, error => console.log(error) /* ... or whatever */)
  .retryWhen(error => {
    return error.delay(500).take(5);
  })
  ...

Upvotes: 2

alexKhymenko
alexKhymenko

Reputation: 5598

What you can do is add do operator

error.delay(500).do(() => {console.log('try')}).take(5);

Upvotes: 3

Related Questions