Created
May 7, 2022 11:56
-
-
Save mishimay/3d88f2bd99e598bda1b0b4d49ee1b9cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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