Junior — Middle
Kuidas saab katkestada asünkroonse operatsiooni täitmise?
sobes.tech AI
Vastus AI-lt
In iOS, the following approaches are commonly used to interrupt an asynchronous operation:
-
Cancel URLSession task — if the asynchronous operation is related to a network request, you can call the
cancel()method on theURLSessionTaskobject. -
Use
DispatchWorkItem— when working with GCD, you can create aDispatchWorkItemand callcancel()to attempt to interrupt its execution. -
Combine and Swift Concurrency — in Combine, you can cancel the subscription (
AnyCancellable), and in Swift Concurrency (async/await), you can useTaskand callcancel().
Example with Task in Swift Concurrency:
let task = Task {
for i in 1...10 {
try Task.checkCancellation() // Cancellation check
print(i)
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}
// Later, to cancel:
task.cancel()
It is important that the asynchronous operation implements a cancellation check, otherwise the operation will continue to execute.