0

Consider the code below

func test() -> SignalProducer<String, Error> {
    return SignalProducer<String, Error> { observer, _ in
        ...
    }
}

test()
    .on(value: { s in
        print(s)
    })
    .retry(upTo: 2)
    .start()
}

Is there a built-in way to retry n times, then (if it failed all the tries) execute some callback?

It's of course possible to introduce a local counter and count the failures in .on(failed: _) and then do something if the counter equals n+1, but is there some other way to do it?

Buddy
  • 1,808
  • 3
  • 19
  • 28

1 Answers1

2

retry(upTo:) passes along the error once it's reached its retry limit, so you can use one of the start methods that allows you to handle values and an error. For example, using startWithResult you could do this (note I haven't tested this code, but it should give you the idea):

test()
    .retry(upTo: 2)
    .startWithResult { result in
        switch result {
        case let .success(value):
            print(value)
        case let .failed(error):
            // handle error here
        }
    }
jjoelson
  • 5,771
  • 5
  • 31
  • 51
  • What's important here is the order, adding the `.retry` before the `.on` handlers passes the last error only (the desired effect in this case). I somehow missed that. – Buddy Apr 28 '17 at 12:59
  • 1
    Yeah, each operator actually creates a new signal/producer that wraps the previous one with some logic or transfomation. So `retry` in your original code is going to retry the producer as defined by all the code that comes before it, which includes the `on` side effects. – jjoelson Apr 28 '17 at 14:25