Tuesday, November 29, 2022
HomeIOS Developmentios - Retry after Delay for scheduled job in Mix

ios – Retry after Delay for scheduled job 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.

Concept:

  • 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 options 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: .principal, in: .widespread).autoconnect()
var session =  URLSession.shared.dataTaskPublisher(for: URL(string: "https://google.com")!).map(.information).eraseToAnyPublisher()

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


        }
    }, receiveValue: { information in
        print("success")
        
       
    })

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments