Sobes.tech
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:

  1. Cancel URLSession task — if the asynchronous operation is related to a network request, you can call the cancel() method on the URLSessionTask object.

  2. Use DispatchWorkItem — when working with GCD, you can create a DispatchWorkItem and call cancel() to attempt to interrupt its execution.

  3. Combine and Swift Concurrency — in Combine, you can cancel the subscription (AnyCancellable), and in Swift Concurrency (async/await), you can use Task and call cancel().

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.