Skip to content

Commit 88179ba

Browse files
Merge pull request #2 from SwiftPackageIndex/async-attempt
Add async overload
2 parents d82d46d + 3499d0f commit 88179ba

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Sources/Retry/Retry.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,35 @@ public enum Retry {
5252
}
5353
throw Error.retryLimitExceeded(lastError: lastError)
5454
}
55+
56+
@discardableResult
57+
public static func attempt<T>(_ label: String,
58+
delay: Double = 5,
59+
retries: Int = 5,
60+
logger: RetryLogging = DefaultLogger(),
61+
_ block: () async throws -> T) async throws -> T {
62+
var retriesLeft = retries
63+
var currentTry = 1
64+
var lastError: String?
65+
while true {
66+
if currentTry > 1 {
67+
logger.onStartOfRetry(label: label, attempt: currentTry)
68+
}
69+
do {
70+
return try await block()
71+
} catch {
72+
logger.onError(label: label, error: error)
73+
lastError = "\(error)"
74+
guard retriesLeft > 0 else { break }
75+
let delay = backedOffDelay(baseDelay: delay, attempt: currentTry)
76+
logger.onStartOfDelay(label: label, delay: Double(delay))
77+
sleep(delay)
78+
currentTry += 1
79+
retriesLeft -= 1
80+
}
81+
}
82+
throw Error.retryLimitExceeded(lastError: lastError)
83+
}
5584
}
5685

5786

Tests/RetryTests/RetryTests.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,18 @@ final class RetryTests: XCTestCase {
7474
XCTAssertEqual(called, 4)
7575
}
7676

77+
func test_attempt_async() async throws {
78+
func dummyAsyncFunction() async { }
79+
var called = 0
80+
81+
// MUT
82+
try await Retry.attempt("", delay: 0, retries: 3) {
83+
await dummyAsyncFunction()
84+
called += 1
85+
}
86+
87+
// validation
88+
XCTAssertEqual(called, 1)
89+
}
90+
7791
}

0 commit comments

Comments
 (0)