How to Create Callback-like Behavior Using AsyncStream in Swift

No more relying on closures.

Lee Kah Seng
4 min readJul 18, 2023

This article is originally published at swiftsenpai.com

Without a doubt, Swift Concurrency has revolutionized the way we handle asynchronous code in Swift. One powerful component of it is AsyncStream, a specialized form of AsyncSequence that is well-suited to achieve callback- or delegate-like behavior using the async/await syntax.

Prior to Swift Concurrency, developers had to rely on closures to trigger callbacks and inform callers about certain events during asynchronous operations. However, with the introduction of AsyncStream, this closure-based approach can now be replaced with a more intuitive and straightforward async/await syntax.

In this article, let’s explore a simple yet illustrative example of how AsyncStream can be utilized to track the progress of a download operation. By the end of this reading, you will have a good understanding of how AsyncStream works and start using it in your own projects.

So, without further ado, let’s get started.

The Sample App

In order to showcase the power of AsyncStream, let’s create a sample app that will simulate a download operation and display the download progress using a progress…

--

--

Lee Kah Seng
Lee Kah Seng

Written by Lee Kah Seng

Support me by becoming a Medium member: https://leekahseng.medium.com/membership ⦿ 🇲🇾 Creator of https://swiftsenpai.com ⦿ iOS developer since 2011

Responses (1)