Today I finished a WWDC session with the swift team and they basically clarified what's really going on in my code. Unfortunately the session is only 30 min long so I didn't get to ask all the questions. Hoping that someone who is a swift guru can answer it here instead.
Code we discussed is like this:
func calledFromMainThread() {
// Main
Task {
// Main
await withTaskGroup(of: Void.self) { group in
// Main
group.addTask {
// Wont be on main
guard let result = await self.backgroundTask() else { return }
await MainActor.run {
//Main
withAnimation {
self.updateUI()
}
}
}
}
So basically I had them clarify line by line which code will run on the main thread.
I found it really interesting that for example, withTaskGroup despite being await, runs on the main thread. Meanwhile addTask() does not. So first question, how can I discover things like this on my own without calling Apple? I don't see where the API docs specify these things. At least with Task() there's a paragraph somewhere that tells you it inherits the Mainactor.
Second question. To this day, because I'm so new that I still don't fully understand what Task does in terms of thread. I've read the WWDC videos and some swift books. Couldn't grasp it coming from other programming languages. According to the docs, Task creates a unit of work. But what does that mean?
For example if you have
print("1")
Task {
print("2")
}
print("3")
- If it was originally called from the main thread (and thus inheriting mainactor), Is 2 expected to run immediately after 1? Can code run in between 2 and 1?
- If it was NOT on the main thread. Is it possible that 2 and 1 run on different threads?
- If it was originally called from the main thread (and thus inheriting mainactor), Is 3 expected to run immediately after 1? Can code run in between 3 and 1?
- If it was NOT on the main thread. Is it possible that 3 and 1 run on different threads?