Better Programming

Advice for programmers.

Follow publication

How to Bridge Async/await Functions to Combine’s Future Type in Swift

Natascha Fadeeva
Better Programming
Published in
2 min readAug 29, 2022

When working with asynchronious code in Swift, we might have to find ways to mix and connect different asynchronious patterns like using the Combine framework together with Swift’s async/await API.

In this article, we’ll look at how to call async-marked functions within Combine based APIs.

Let’s look at the following async function which loads a user from server with the async/await pattern.

To implement the same behaviour with Combine, its Future publisher comes in handy. A future is initialized with a closure that takes a Future.Promise. After doing some asynchronous work, we call that closure with a Result that is either a success or a failure. Combine then automatically maps the result into proper publisher events.

Let’s look at how the async function above could be implemented with a Future publisher:

But since we already have an implementation that loads a user, we’d like to avoid duplication writing the same logic twice.

So let’s try to find a more generic solution, that allows us to convert an async func to a Future publisher.

In the code above, we extend the Future type with a convenience initializer that allows us to initialize an instance with an async closure. Applied to our example:

For non-throwing async functions, we could add another extension:

With a generic solution like this, we now have the possibility to use it on any async function to bridge it to Combine’s Future type.

Originally published at https://tanaschita.com.

Sign up to discover human stories that deepen your understanding of the world.

Natascha Fadeeva
Natascha Fadeeva

Written by Natascha Fadeeva

Writing articles about iOS and Swift programming. Not active here anymore. Checkout tanaschita.com for up-to-date articles.

No responses yet

Write a response