Open utterances-bot opened 3 years ago
This is a fantastic article. Looking forward to the following ones.
Regarding the async download started in viewDidAppear, how would you cancel it in viewWillDissapear?
Regarding the async download started in viewDidAppear, how would you cancel it in viewWillDissapear?
This is something you'd do with unstructured tasks (I'll cover this in a future article), but async {}
returns a Task.Handle<T, E: Error>
that you can store and manually use to cancel tasks. Note that when used this way it will launch a concurrent task.
So in short you will have a variable that will hold your handle to the task as a property.
private var prepareTask: Task.Handle<Void, Never>?
On viewDidAppear
:
prepareTask = async {
let details = // await downloadImageAndDetail
// Update outlets/UI
prepareTask = nil
}
And on viewDidDisappear
:
prepareTask?.cancel()
Sorry for the lazy formatting, I'm on my phone π
I'll cover this in a future article in the series, but if you don't wanna wait, the Explore structured concurrency in Swift WWDC2021 session covers this at around the 20 minute mark.
Thanks that looks right now and now matches what Apple recommended in the session. I don't think you need a new tutorial though, you could simply correct the viewDidAppear
snippet in this one.
Great article. Looking forward to the following ones. Thanks ππ»
Thanks for the article! Typo: structured concurrency, unstructured currency
. Currency
instead of concurrency
.
If I had to explain async/await in as many few words as possible
. many
is a mistake here I guess?
@tagirkaz thanks, I'll fix both.
@AndyIbanez thank you for a great article!
Very good article.
It is recommended to update viewDidAppear
as written in the downloaded source code.
It should be
@MainActor override func viewDidAppear(_ animated: Bool)
"One final important note about await: Itβs not guaranteed that the same thread that executed the code above it is the same one that will execute the code below it (commonly called the continuation)."
This is very useful, but I had some doubts when looking at the sample code. Why is there no code>@MainActor</code added here, and then I downloaded the source code and found that it is not consistent.
@xjpch thanks for your comment. The reason MainActor is not mentioned was because I wanted to avoid talking too much about topics that aren't covered in this article. Now that I have finished the series, I will revisit how some concepts are explained, and I may add an explanation of MainActor here.
Nice article! thanks
I am from .NET with exp 4 years and working on iOS stack at the moment. Reading about async await in swift so far I can say that .NET async and Swift async are really close to each other. However .NET async is not interpreted as concurrency at all. It is all about thread utilisation efficiency
Understanding async/await in Swift β’ Andy Ibanez
https://www.andyibanez.com/posts/understanding-async-await-in-swift/