3

I'm trying to understand how to consume observable sequences and how to recover from errors.

My example is a bit contrived but my real implementation is a bit too complex to show here. Anyway, I have someObservable that emits values when the user clicks in the UI. This should trigger a request to the API (GET/POST/etc). The problem is that if the API returns an error, postData isn't called anymore after that.

I've make an example here that shows the problem. I've found that I can use Rx.Observable.of instead of Rx.Observable.throw to keep things running. But that will emit a value to the subscribe function. And in my real application postData is a service that is reused by multiple parts of the application and I'm not sure that I want to use of instead of throw there.

So my question is, how do you normally handle things like these?

let someObservable = Rx.Observable.timer(1, 1000);

someObservable
.switchMap(data =>  {
  return postData(data);
})
.catch(error => {
  console.log("POST failed");
})
.subscribe(val => console.log("Success: " + val));

function postData(data) {
  console.log("Will post " + data);

  if (data !== 2) {
    return Rx.Observable.of(true);
  }
  else {
    return Rx.Observable.throw(new Error("400 Bad Request or something"));
  }
}

http://jsbin.com/naroyeyive/3/edit?js,console

Joel
  • 8,502
  • 11
  • 66
  • 115
  • 1
    Catch immediately: `return postData(data).catch(...)` Modified bin: http://jsbin.com/rujakoguro/3/edit?js,console – artur grzesiak Mar 07 '17 at 09:12
  • @arturgrzesiak Ok, that seems to work! Do you think you could write an answer and explain briefly _why_ I need to catch there and not like I do in my code? – Joel Mar 07 '17 at 09:33

1 Answers1

4

If you want to send the request again, you may want to look into retry and retryWhen instead of catch.

catch will use the returned Observable as new "source". See this bin for an example.

retry(When) will "re-subscribe" whenever an error occurs, based on the configuration you pass to the operators. You can find examples and more information here: https://www.learnrxjs.io/operators/error_handling/retrywhen.html

Sebastian Sebald
  • 16,130
  • 5
  • 62
  • 66