Skip to content

Commit

Permalink
onEach modifier (#37)
Browse files Browse the repository at this point in the history
* Implement onEach modifier #36

* Update README.md
  • Loading branch information
PierreMardon committed Aug 20, 2024
1 parent 3a884f7 commit e2d767f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions Sources/SwiftRetrier/Util/Retrier+OnEach.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Combine

public extension Retrier {

func onEach(handleEvent: @escaping (RetrierEvent<Output>) -> Void) -> Self {
var subscription: AnyCancellable?
subscription = publisher()
.sink(receiveCompletion: { _ in
subscription?.cancel()
}, receiveValue: handleEvent)
return self
}
}

0 comments on commit e2d767f

Please sign in to comment.