ios – Retry after Delay for scheduled activity in Mix


I wish to schedule API in sure interval of time, and if that API fails I wish to retry that api after sure time and if it hits max retry it ought to cease calling API, however whether it is success it has to proceed in scheduled time.


  • two streams, Timer and dataTaskPublisher.
  • Timer will drive the dataTaskPublisher.
  • if dataTaskPublisher fails:
  • reschdeule timer with some delay()
  • if maxretry rely reached cease timer(which can cease dataTaskPublisher)

I’m kinda misplaced to orchestrate two streams, Any strategies for pattern can be very useful.
Apologies for my newbie tryout.

var cancellables: AnyCancellable
let interval = 2
let maxRetry = 2
let delay = 5

var timer = Timer.publish(each: TimeInterval(interval), on: .major, in: .frequent).autoconnect()
var session =  URLSession.shared.dataTaskPublisher(for: URL(string: "")!).map(.knowledge).eraseToAnyPublisher()

cancellables = timer.flatMap{ _ in
    return session.catch { _ -> AnyPublisher<Information, URLError> in 
        return Publishers.Delay(upstream: session,
                                interval: .seconds(delay), tolerance: 1,
                                scheduler: RunLoop.major).print("retrying").retry(maxRetry).eraseToAnyPublisher() 
}.sink(receiveCompletion: { comp in
        if case let .failure(err) = comp {
            print("=============================That is error (err)")
            // This does not set off.  

    }, receiveValue: { knowledge in


Leave a Reply