Daily iOS
Concurrency

Leaving a loading screen

When the user enters the detail screen, it calls an API like this and shows the data.

final class DetailViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        api.fetchDetail(id: id) { result in
            self.render(result)
        }
    }
}

The interviewer asks: "What happens if the user taps back before the response arrives?" Explain the problems this code can cause, and how you'd keep the request for a screen the user left from going to waste.

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A response that arrives after the user goes back updates a deallocated (or different) screen, or the strong capture keeps the screen alive, and the request itself keeps running and wastes resources. Fix: keep the request as a Task and cancel it when the screen closes (SwiftUI .task does it automatically), use [weak self], and branch on CancellationError.

Share a question