Parallelization with async let

AsyncLearn
2 min readJan 15, 2024

--

One of the ways to provide a better user experience is by utilizing parallelization to make our apps more responsive.

Using async let, we can execute multiple asynchronous operations simultaneously.

How to use async let

Imagine you have two asynchronous functions, one called getInt() that returns an integer after performing some calculations, and another called getString() that is also asynchronous but returns a text string. To fulfil a requirement, you need to print the results of each of these two functions.

One option could be to execute these two functions as follows:

let number = await getInt()
let text = await getString()

print("\(number) \(text)")

This would work, but to execute the second function, we have to wait for the first one to return, so we are not making efficient use of parallelization resources.

If we want to call both of them in parallel, we would have to use the following code:

async let numberOperation = getInt()
async let textOperation = getString()

let (number, text) = await (numberOperation, textOperation)

print("\(number) \(text)")

With this, we store the results in the number and text variables just like in the previous code. However, thanks to async let, the functions will run in parallel, allowing us to complete the operations in less time.

Things to consider

  • If any of the asynchronous functions can throw exceptions, we should use try or one of its variations, such as try? or try!.
  • async let is very convenient for a small number of tasks; if we have many tasks, it's better to consider using TaskGroup.
  • Functions that use async let should be independent, and the order in which they execute should not matter.

If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/paralelizacion-con-async-let/

--

--

AsyncLearn
AsyncLearn

Written by AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.

No responses yet