一个用于在同步环境中使用异步API的Swift库。
- 兼容iOS和macOS
- 无死锁
- 支持基于回调的异步代码
- 支持基于swift-concurrency的异步代码
Resyncer通过将异步工作卸载到不同的线程(通过使用OperationQueue或利用swift-concurrency Task)来暂停当前线程执行,等待异步工作完成,从而帮助您在同步环境中调用异步代码。
因为Resyncer会阻塞调用线程,请确保不要在主线程中使用它。
如果您有一个异步函数,它使用Swift Result
(或也可以不使用Result
,您自己可以构造它)将值发布到提供的回调中
func asyncWork(_ completion: @escaping (Result<Int, Error>) -> Void) { ... }
您可以使用Resyncher在同步环境中获取产生的值
let x = try resyncer.synchronize { callback in
self.asyncWork { result in
callback(result)
}
}
如果您有一个返回值的异步函数
func asyncWork() async throws -> Int { ... }
您可以使用Resyncher在同步环境中获取产生的值
let x = try resyncer.synchronize { callback in
try await self.asyncWork()
}
将Resyncer
框架的依赖添加到您的Podfile
pod 'Resyncer', '~> 1.0.0'
在Swift包中将其作为依赖添加
dependencies: [
.package(url: "https://github.com/danielepantaleone/Resyncer.git", .upToNextMajor(from: "1.0.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.