|< How to fix the error “async call in a function that does not support concurrency”||How to loop over an AsyncSequence using for await >|
Swift provides several ways of receiving a potentially endless flow of data, allowing us to read values one by one, or loop over them using
while, or similar.
The simplest is the
Sequence protocol, which continually returns values until the sequence is terminated by returning
nil. Lots of things conform to
Sequence, including arrays, strings, ranges,
Data, and more. Through protocol extensions
Sequence also gives us access to a variety of methods, including
map(), and others.
AsyncSequence protocol is almost identical to
Sequence, with the important exception that each element in the sequence is returned asynchronously. I realize that sounds obvious, but it actually has two major impacts on the way they work.
First, reading a value from the async sequence must use
await so the sequence can suspend itself while reading its next value. This might be performing some complex work, for example, or perhaps fetching data from a server.
Second, more advanced async sequences known as async streams might generate values faster than you can read them, in which case you can either discard the extra values or buffer them to be read later on.
So, in the first case think of it like your code wanting values faster than the async sequence can make them, whereas in the second case it’s more like the async sequence generating data faster than than your code can read them.
AsyncSequence have lots in common: the code to create a custom one yourself is almost the same, both can throw errors if you want, both get access to common functionality such as
reduce(), and you can also use
continue to exit loops over either of them.
SPONSORED From August 2nd to 8th you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Link copied to your pasteboard.