Jacob’s Tech Tavern

Jacob’s Tech Tavern

Migrating Combine to AsyncAlgorithms

Future-proof your pipeline operations

Jacob Bartlett's avatar
Jacob Bartlett
Oct 07, 2024

It’s no secret.

I’m a Combine fanboy.

I had a chip on my shoulder after missing the RxSwift bandwagon. Therefore, when Combine came out in 2019, I got serious shiny-object syndrome and used it wherever I could.

Then, in 2021, Swift Concurrency (finally) released, with ergonomics which drastically outclassed Combine for many simple use cases. 

Combine still held a cherished place in my heart. I’d built my whole network stack with the framework, and came up with all manner of excuses to resist transitioning.

Once the AsyncAlgorithms package was published in 2022, there was really no excuse left: much of the functionality in Combine was now available in Swift Concurrency.

Today, I’ll demonstrate how to migrate your Combine code over to AsyncAlgorithms, with a fully open-source tutorial project you can code along with. 

If you, like me, need to wean yourself off Combine, then code along from Before to After.

The Combine Project structure 

The Combine project (Before) is a familiar layered architecture you might find in many indie projects, although you probably aren’t lazy enough to leave ContentView as the default name.

  • UI layer — ContentView & ContentViewModel

  • Data access layer — ContentRepo 

  • Networking layer — all the APIs 

While this project is pretty basic; it demonstrates a nice mix of various Combine use cases you might find in your projects.

These use cases include: 

  • Displaying a notification badge from a couple of data sources.

  • Displaying the progress of a long-running download.

  • Fetching and displaying a username from an API call.

Async Algorithms 

There’s one protocol you need to understand to really get to grips with AsyncAlgorithms: AsyncSequence.

AsyncSequence works a lot like the regular Sequence protocol in the Swift Standard Library: it provides an asynchronous version of the Iterator protocol that offers async iterated access to the next() element.

This iteration can be invoked using the for-await-in syntax sugar.

AsyncSequence should be very familiar if you’re coming from Combine publishers: both deal with streams of values over time. Many of the algorithms in the AsyncAlgorithms package therefore serve as drop-in replacements for corresponding Combine operations.

If you want a more detailed primer on AsyncSequence, and concurrency tools in general, check out this piece I wrote for my friends at Emerge Tools: Async await in Swift: The Full Toolkit.

Let’s jump into the tutorial now. 

And code along, dammit!

Starting from Before, the original Combine project, import the AsyncAlgorithms package from Github. 

Importing AsyncAlgorithms using Swift Package Manager from Xcode

Let’s go through each use case step-by-step and migrate Combine over to their modern AsyncAlgorithm equivalents. 

Combining data sources 

Let’s say you’re a social app, an email app, or a personal finance app — the key engagement hook is notifications, often with a single menu which contains them.

The most popular UI pattern is decorating the notification menu button with a badge and number, which counts all the notifications. 

Migrating the Repository

This number pulls together various data sources in order to get the correct number, which we can set up in our trusty Repository.

var chatNotificationsSubject = CurrentValueSubject<[Notification], Never>([])
var friendNotificationsSubject = CurrentValueSubject<[Notification], Never>([])

func streamChatNotifications() {
    Task {
        let chatNotifications = try? await chatAPI.getUnreadChatMessages()
        chatNotificationsSubject.send(chatNotifications ?? [])
    }
}

func streamFriendNotifications() {
    Task {
        let friendNotifications = try? await friendsAPI.getFriendNotifications()
        friendNotificationsSubject.send(friendNotifications ?? [])
    }
}

Just because we’re migrating, doesn’t mean we need to rip out all the Combine code at once. You might even be working with a third party SDK. What’s important here is taking Combine out of our public interfaces — and leaving it as an implementation detail.

Fortunately, it’s easy to seamlessly convert Combine publishers into Swift-Concurrency-friendly AsyncSequences using the values modifier.

This property was actually the last update Apple ever gave to Combine, in 2021.

🥲

The .values modifier on any Publisher returns an AsyncPublisher, which conforms to AsyncSequence

To keep Combine out of the interface, we can make the Combine subjects private: 

private var chatNotificationsSubject = CurrentValueSubject<[Notification], Never>([])
private var friendNotificationsSubject = CurrentValueSubject<[Notification], Never>([])

And use computed properties which convert them into AsyncSequences which can be consumed downstream:

var chatNotificationsSequence: AsyncPublisher<AnyPublisher<[Notification], Never>> {
    chatNotificationsSubject.eraseToAnyPublisher().values
}
    
var friendNotificationsSequence: AsyncPublisher<AnyPublisher<[Notification], Never>> {
    friendNotificationsSubject.eraseToAnyPublisher().values
}

Since we’re leaving the internal implementation unchanged, we don’t even need to modify our API code in this instance. The conversion is relatively seamless once you get your head around type erasure.

Migrating the View Model

In the view model, we originally used the eponymous combineLatest to merge the streams together. This is Combine’s bread-and-butter: publishing values from multiple data sources and combining them together.

This modifier publishes pairs of values each time either publisher sends anything. For our notification badge, this means we can always be sure it’s combining the total number of new notifications from each source, such as friend requests, chat messages, and likes.

This ensures our users see the correct value for the badge.

 private func subscribeToNotifications() {
    repo.chatNotificationsSubject
        .combineLatest(repo.friendNotificationsSubject)
        .map { $0.0.count + $0.1.count }
        .receive(on: RunLoop.main)
        .assign(to: \.notificationCount, on: self)
        .store(in: &cancellables)
}

The most critical thing to understand when moving from Combine to AsyncAlgorithms is the way we iterate through values.

Instead of handling streams of values with .sink, we’re now iterating through an AsyncSequence using the for-await-in syntax.

Wait, that wasn’t the most important thing!
The most important thing is to import AsyncAlgorithms. But the iteration syntax is definitely #2. 

Now that our imports are in order, we can merge the AsyncSequence streams together in our view model.

We combine the streams from the repo using the combineLatest() algorithm, which has virtually identical syntax to the Combine form. 

private func streamNotificationCount() async {
    for await notificationsCount in combineLatest(
        repo.chatNotificationsSequence,
        repo.friendNotificationsSequence
    ) { ... }
}

If you aren’t familiar with the behaviour of combineLatest, printing the output above looks a little like this (mapping just the id property):

// no notifications to start with
([], []) 

// friend notifications published
([], ["4", "5", "6", "6"]) 

// chat notifications arrive, both sets published
(["1", "2", "3"], ["4", "5", "6", "6"]) 

Migrating the map is actually much easier — it isn’t even an AsyncAlgorithm; it’s just the existing standard library implementation of map on a Sequence.

@MainActor
private func streamNotificationCount() async {
    for await notificationsCount in combineLatest(
        repo.chatNotificationsSequence,
        repo.friendNotificationsSequence
    ).map({
        $0.0.count + $0.1.count
    }) {
        self.notificationCount = notificationsCount
    }
}

Since we’re assigning a property on our observable view model, we put this method on the @MainActor to ensure thread safety. 

This single @MainActor attribute neatly replaces the .receive(on: RunLoop.main) operation. The for-await-in syntax serves as a suspension point between each iteration of the stream — the waiting itself is happening off the main thread.

Streams and throttling 

Many apps include some kind of loading bar, or progress indicator, for any non-trivial download or processing task. This simple UI element can yield a big UX improvement by making the app appear more responsive. 

What we don’t want to do, however, is spam the UI with more updates than we have frames per second. So, even if we are inundated with 1000 progress updates per second, we should only update the UI when the user will actually notice.

Migrating the Repository

Our original download listener is doing what Combine does best: handling a rapid stream of delegate callbacks from a closure-based API. This updates the download percentage on our UI. 

var downloadSubject = PassthroughSubject<Double, Never>()
private let downloadAPI = DownloadAPI()

func performDownload() {
    Task {
        await downloadAPI.startDownload { [weak self] percentage in
            self?.downloadSubject.send(percentage)
        }
    }
}

To migrate this to pure Swift Concurrency, first we want to convert the Combine stream into an AsyncStream with a Continuation.

AsyncStream is a special concrete generic type which conforms to the AsyncSequence protocol, but gives us full control over creating and sending values. This allows it to handily take up the mantle of “wrapping callback-based APIs”. 

Continuations are a runtime entity in Swift Concurrency: lightweight objects that store state at async suspension points and allow resumption in the future.

Continuations manage a suspension point, and we manually send values to the stream using yield(). This triggers the next() value in AsyncStream’s iterator to be sent.

func performDownload() async -> AsyncStream<Double> {
    AsyncStream { continuation in
        Task {
            await downloadAPI.startDownload { percentage in
                continuation.yield(percentage)
            }
            continuation.finish()
        }
    }
}

This, admittedly, isn’t the most intuitive code if you aren’t used to AsyncStream. 

In short, we are replacing Combine’s subject.send(value) with AsyncStream’s continuation.yield(value).

Subscribe for free to continue reading

Enter your email and get every post from Jacob’s Tech Tavern.
Already have an account? Sign in
© 2026 Jacob Bartlett · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for writing, podcasting, and media founders.