retry는 에러발생시 지정한 횟수만큼 자동으로 업스트림 Publisher에게 재발행을 요청하는 Operator 에요

특징

사용

여기서는 retry를 3번 시도하되, 3번 미만의 시도에서는 에러를 발생시키고 3번째 시도에서 성공하는 시나리오를 작성해볼게요.

var attempts = 0
let retryablePublisher = Deferred {
  Future<Int, Error> { promise in
    attempts += 1
    if attempts < 3 {
      print("error 발생 \\(attempts)번째 시도")
      promise(.failure(URLError(.notConnectedToInternet)))
    } else {
      promise(.success(42))
    }
  }
}

retryablePublisher
  .retry(3)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .finished:
      print("Completed successfully")
    case .failure(let error):
      print("Failed with error: \\(error)")
    }
  }, receiveValue: { value in
			print("\\(value)")
  })
  .store(in: &cancellables)
  
  
// 결과
error 발생 1번째 시도
error 발생 2번째 시도
42
finished