Lesson - 8 Structured Concurrency(Swift Concurrency)
So far we have created independent tasks.
Task {
// task
}
what if we wants task to be have child-parent relationship?
That's where structured concurrency comes in. Here parents manages the children's.
This give us important guarantees around:
- Life Time
- Cancellation
- Errors
- Completion
We will start with simple concurrency tool async let
suppose we have:
func fetchUser() async -> String {
return "Armaan"
}
func fetchPosts() async -> [String] {
return ["Post 1", "Post 2"]
}
we can do it them sequentially
fetchUser
████████
↓
done
↓
fetchPosts
████████
↓
done
If each task takes 2 seconds then roughly it would take 4 seconds.
But these operations do not depend on each other.
We can run them concurrently.
async let user = fetchUser()
async let posts = fetchPosts()
let result = await(user, posts)
Now,
fetchUser
████████
↓
└──────── done
fetchPosts
████████
↓
└──────── done
They can make progress concurrently. If each takes roughly 2 seconds it would take approximately 2 seconds rather than 4 seconds.
Top comments (0)