RetryKit

RetryKit 是一个小巧的软件包,它实现了一种灵活的机制,用于根据策略和输出来重试工作(当使用例如 NSOperation 显得过度时)。

它的编写遵循两个原则:简洁优雅

安装

RetryKit 使用 Swift Package Manager 分发。 要将其安装到项目中,请将其作为依赖项添加到您的 Package.swift 清单中。

let package = Package(
    ...
    dependencies: [
        .package(url: "https://github.com/marcelvoss/RetryKit.git", from: "0.1.0")
    ],
    ...
)

然后,在您想使用它的任何地方导入 RetryKit

import RetryKit

就这么简单! 🎉

用法

使用 RetryKit 非常容易。

工作被封装在 Task 对象中。 这些对象除了抽象任何工作、提供输出验证闭包并跟踪它们被重试的次数之外,不做任何其他事情。 它们非常简单,但具有很大的灵活性,这反映在它们的初始化器中。

let task = Task<Result<String, Error>>(maximumAttempts: 5, work: { output in
    // perform any synchronous or asynchronous work
    // and execute the output closure with your result
    output(.failure(yourProducedError))
}, outputValidation: { output in
    // perform any validation and return a flag whether a retry should be performed
    switch output {
        case .success:
            return false
        case .failure:
            return true
    }
})

输出验证闭包在重试过程中被调用,传入产生的输出值,并允许逐个定制尝试的条件。 因此,它允许简单但也相当复杂的条件。

Task 对象由 Retrier 对象分派。 Retrier 对象同样简单。 它们只有一个责任:在适当的时候(由输出验证闭包和策略决定)分派任务。

策略

RetryKit 附带三种内置的不同重试策略:immediate, after(delay: TimeInterval), .custom((Int) -> TimeInterval)。 这些策略应该涵盖几乎所有情况。

.immediate

.immediate 是最简单的。 所有工作都会立即重试,中间没有任何延迟。 当多次重复重试不是问题时,您可能想要使用此策略。

after(delay: TimeInterval)

after(delay: TimeInterval) 基本上按照您阅读其接口时的预期工作。 在尝试之间经过恒定延迟后,工作会被重试。

.custom((Int) -> TimeInterval)

.custom((Int) -> TimeInterval) 允许这三种策略中最大的自定义程度。 尝试之间的延迟由您自己使用到目前为止发生的重试次数来提供/计算。

当您关心为其添加一些随机性时,自定义策略通常最有用,并且允许在尝试之间使用 指数退避 延迟。

作者

这是由 @marcelvoss 构建的,并受到了我为 SumUp 商户应用程序构建的类似工作的启发。