Skip to content

Instantly share code, notes, and snippets.

@mishimay
Created May 7, 2022 11:56
Show Gist options
  • Save mishimay/3d88f2bd99e598bda1b0b4d49ee1b9cf to your computer and use it in GitHub Desktop.
Save mishimay/3d88f2bd99e598bda1b0b4d49ee1b9cf to your computer and use it in GitHub Desktop.
func fetchData(url: URL) async throws -> Data {
let cancellables = NSMutableSet()
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
let cancellable = APIClient()
.request(url: url)
.sink { completion in
switch completion {
case .failure(let error):
continuation.resume(throwing: error)
case .finished:
break
}
} receiveValue: { data, response in
continuation.resume(returning: data)
}
cancellables.add(cancellable)
}
} onCancel: {
cancellables.removeAllObjects()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment