Created
May 10, 2022 14:01
-
-
Save robertmryan/182d74de1f0bbafbd0a53bfc64f94785 to your computer and use it in GitHub Desktop.
This file contains 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
var task: Task<Void, Error>? | |
func updateLabelAfterAPICall(initialValue: String) { | |
task?.cancel() // just in case | |
task = Task { [weak self] in | |
try await Task.sleep(nanoseconds: 5_500_000_000) | |
self?.label.text = "New Value after 5.5 seconds passed" | |
} | |
} | |
override func viewDidDisappear(_ animated: Bool) { | |
super.viewDidDisappear(animated) | |
task?.cancel() | |
} |
But the salient points in the above, as in matt’s original answer, are that we
- remove the
?
from thetry?
; - use
[weak self]
capture list in theTask
; - keep reference to the
Task
; and cancel
the task when the view disappears.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, I transitioned this back to
viewDidDisappear
, rather thanviewWillDisappear
because the former is called when the view disappears, but the latter will happen when the view might disappear. (This is a distinction that is only relevant in cancelable, interactive transitions, but it’s just good practice to limitviewWillDisappear
to only offset those actions that were initiated inviewWillAppear
.)