封装遗留回调为异步序列(AsyncSequence)
使用 UnsafeContinuation 与 AsyncStream 桥接基于回调的 API 为现代异步序列。 · 难度:入门 · +10XP
封装遗留回调为异步序列(AsyncSequence)
很多系统框架仍使用 @escaping 回调或 delegation 模式。本教程将教你如何将一次性回调转化为 AsyncThrowingStream,以及如何将多次回调(如位置更新、下载进度)转化为 AsyncSequence。你会学到背压管理、取消传播以及如何使用 withUnsafeContinuation 精确控制生命周期。
import CoreLocation
class LocationBridge {
private let manager = CLLocationManager()
func locations() -> AsyncStream {
AsyncStream { continuation in
let delegate = LocationDelegate { location in
continuation.yield(location)
}
manager.delegate = delegate
continuation.onTermination = { _ in
self.manager.stopUpdatingLocation()
}
manager.startUpdatingLocation()
}
}
}