How to use Async Sequence and AsyncStream in Swift

Concurrency with async/await — Part 4

Tim Dolenko
Axel Springer Tech

--

👆watch it if you prefer video

What if you could have an array of events? What if you could use a for-each loop to iterate it?

Let’s take a simple example. Let’s say we have a class that produces a number every second:

How would you turn this class into a sequence of events? We will use AsyncStream for that:

This way you can turn almost any class or API you have into an async sequency.

How we would use it?

Inside the initializer of MagicButtonViewModel, please add a for-in loop:

You can also iterate with for-in over other sequences of events like NotificationCenter.default.notifications(named:) for example! Try it out!

In the view add:

Button {
viewModel.sendNotification()
} label: {
Text("🪄 Play")
.font(.title)
}
.padding()

Inside the viewModel add:

With some extensions:

Run it!

You can even use methods like .filter, .map, or .first on your array of events:

We see each other in Part 5!

--

--