Resyncer

Cocoapods GitHub release (latest SemVer) GitHub GitHub Workflow Status (with event)

Resyncer 是一个 Swift 库,旨在将异步 API 无缝集成到同步环境中。它允许开发者调用异步代码(无论是使用回调还是 Swift 的 async/await 模式),并阻塞调用线程,直到异步任务完成。这确保在继续同步工作流程之前,结果可用,使其非常适合需要顺序执行但涉及异步任务的场景。

目录

功能亮点

基本用法

Resyncer 使您能够在同步环境中调用异步代码,方法是暂停当前线程直到异步任务完成。它通过将异步工作卸载到单独的线程来实现,可以使用 OperationQueue 或利用 Swift 并发和 Task

因为 Resyncer 将会阻塞调用线程,请确保不要从主线程使用它。

与基于回调的异步代码一起使用

如果您有一个异步函数,它使用 Swift 的 Result 在提供的回调上发布一个值(或者即使没有 Result,您也可以自己构建它)

func asyncWork(_ completion: @escaping (Result<Int, Error>) -> Void) { ... }

您可以使用 Resyncer 在同步环境中获取生成的值

let x = try resyncer.synchronize { callback in
    self.asyncWork { result in
        callback(result)
    }
}

与基于 swift-concurrency 的异步代码一起使用

如果您有一个返回值的异步函数

func asyncWork() async throws -> Int { ... }

您可以使用 Resyncer 在同步环境中获取生成的值

let x = try resyncer.synchronize {
    try await self.asyncWork()
}

安装

Cocoapods

将依赖项添加到您的 Podfile 中的 Resyncer 框架中

pod 'Resyncer', '~> 1.1.0'

Swift Package Manager

将其作为 Swift Package 中的依赖项添加

dependencies: [
    .package(url: "https://github.com/danielepantaleone/Resyncer.git", .upToNextMajor(from: "1.1.0"))
]

贡献

如果您喜欢这个项目,您可以通过以下方式贡献它:

许可证

MIT License

Copyright (c) 2024 Daniele Pantaleone

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.