Example of converting delegate pattern to async/avait
// MARK: - Implementation
class Service {
private var resultBlock: ((String) -> Void)?
func work() async -> String {
await withCheckedContinuation { continuation in
resultBlock = { result in
continuation.resume(returning: result)
}
}
}
}
extension Service: Delegate {
func didComplete(with result: String) {
resultBlock?(result)
}
}
protocol Delegate: AnyObject {
func didComplete(with result: String)
}
class Manager {
weak var delegate: Delegate?
func runResultEvent() {
delegate?.didComplete(with: "Apple")
}
}
// MARK: - Testing
let service = Service()
let manager = Manager()
manager.delegate = service
Task {
try await Task.sleep(for: .seconds(3))
print("2. run result")
manager.runResultEvent()
}
print("1. waiting for result...")
let result = await service.work()
print("3. delegate result:", result)
print("4. done")
// will print:
// 1. waiting for result...
// 2. run result
// 3. delegate result: Apple
// 4. done