From e2d767f6e67b25e58ff9788b6b3465be8f2d943e Mon Sep 17 00:00:00 2001 From: Pierre Mardon Date: Tue, 20 Aug 2024 15:48:22 +0200 Subject: [PATCH] `onEach` modifier (#37) * Implement onEach modifier #36 * Update README.md --- README.md | 20 +++++++++++++++++++ .../SwiftRetrier/Util/Retrier+OnEach.swift | 13 ++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 Sources/SwiftRetrier/Util/Retrier+OnEach.swift diff --git a/README.md b/README.md index 280b732..d753f1a 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,26 @@ let value = try await withExponentialBackoff() Note that you can use `cancellableValue` instead of `value`. In this case, if the task wrapping the concurrency context is cancelled, the underlying retrier will be cancelled. +## Simple events handling + +Retrier events can be handled simply. + +```swift +fetcher.onEach { + switch $0 { + case .attemptSuccess(let value): + print("Fetched something: \(value)") + case .attemptFailure(let failure): + print("An attempt #\(failure.index) failed with \(failure.error)") + case .completion(let error): + print("Fetcher completed with \(error?.localizedDescription ?? "no error")") + } +} +``` + +Keep in mind that the event handler will be retained until the retrier finishes (succeeding, failing or being +cancelled). + ## Combine publishers All retriers (including repeaters) expose Combine publishers that publish relevant events. diff --git a/Sources/SwiftRetrier/Util/Retrier+OnEach.swift b/Sources/SwiftRetrier/Util/Retrier+OnEach.swift new file mode 100644 index 0000000..0351661 --- /dev/null +++ b/Sources/SwiftRetrier/Util/Retrier+OnEach.swift @@ -0,0 +1,13 @@ +import Combine + +public extension Retrier { + + func onEach(handleEvent: @escaping (RetrierEvent) -> Void) -> Self { + var subscription: AnyCancellable? + subscription = publisher() + .sink(receiveCompletion: { _ in + subscription?.cancel() + }, receiveValue: handleEvent) + return self + } +}