Reputation: 3643
As per the new Structured Concurrency in Swift, we can await a API call which is done in an async context, But I want to make multiple API calls simultaneously, for example, currently If add the API calls one after another,
profileData = await viewModel.getProfileData()
userCardData = await viewModel.getCardDetails()
The problem in the above case is CardDetails is fetched only after fetching the profile data.
Upvotes: 12
Views: 8265
Reputation: 3643
It can be achieved using the async let
.
This special syntax allows you to group several asynchronous calls and await them together,
Example,
async let profileData = viewModel.getProfileData()
async let userCardData = viewModel.getCardDetails()
The above statement indicated that profileData
and userCardData
, will be available at some point of time in future, just like a promise.
Now in order to use profileData and userCardData we need to use await, incase the data is fetched and available it would return immediately, or it suspend until the data is available.
The value from the above request can be used like,
let (fetchedProfileData, fetchedUserCardData) = try await (profileData, userCardData)
Upvotes: 22