Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created May 10, 2022 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/182d74de1f0bbafbd0a53bfc64f94785 to your computer and use it in GitHub Desktop.
Save robertmryan/182d74de1f0bbafbd0a53bfc64f94785 to your computer and use it in GitHub Desktop.
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()
}
@robertmryan
Copy link
Author

robertmryan commented May 10, 2022

Note, I transitioned this back to viewDidDisappear, rather than viewWillDisappear 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 limit viewWillDisappear to only offset those actions that were initiated in viewWillAppear.)

@robertmryan
Copy link
Author

robertmryan commented May 10, 2022

But the salient points in the above, as in matt’s original answer, are that we

  • remove the ? from the try?;
  • use [weak self] capture list in the Task;
  • 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