Predict the output
The user types s, sw, swi about 100 ms apart. How many API searches start?
.task(id: query) {
try? await Task.sleep(for: .milliseconds(300))
guard !Task.isCancelled else { return }
results = await API.search(query)
}Hint 1 of 1
What happens to the old task when the id changes?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B 1, for swi
Correct. The first two tasks are cancelled during their sleep and return at the guard.
Why not the others?
- A 3. Each new id cancels the previous task while it is still sleeping.
- C 0. The last task isn't cancelled, so its search runs.
- D 2. Only the final query survives the 300 ms wait.