Convert Swift facades into async/await syntax with continuations

Leverage the power of continuations when converting callback or delegate based APIs

Written in 2021. Some tools and APIs mentioned here have changed since.

The new async/await Swift concurrency API released together with Swift 5.5 was finally unveiled during the WWDC 21 last June. This new architecture fulfilled all the expectations that we iOS developers had, who were eagerly waiting for this since the Swift first release in 2014, and whose hopes got boosted in 2017 with the Swift Concurrency Manifesto by Chris Lattner himself.

From all the new APIs and tools that were introduced, the new async/await syntax, Actors, and Tasks attracted most of the attention from the Swift community. And rightly so, these new additions improved considerably the readability of asynchronous code and the easiness when ensuring thread safety in our apps.

However, there was another mechanism introduced then that didn’t capture so much consideration even though they are very powerful when working together with async/await: Continuations.

What are Continuations?

According to the documentation, Continuations are a mechanism to interface between synchronous and asynchronous code, logging correctness violations.

More precisely, a Continuation is an object that captures the program state at a given point, being able to continue it when it is required.

This might still sound very abstract, but we can learn to appreciate it deeper when considering how Apple implements asynchronous code up until now, with callbacks and the delegate pattern.

Continuations shine with all their brightness when working with these two patterns: they act as a bridge between the old world (callbacks and delegates) and the new one (async/await to achieve a more readable and structured code) by helping to create new async functions facading the old ones.

This is helpful when facading third party libraries or Apple APIs containing these patterns, as in the case that we will see today.

Facading a delegate Based class with Continuations

In our iOS team, we like to facade some Apple or third party developers components with our own ones. The purpose of this pattern is manyfold, but three points really stand out for us:

  • We improve the readability and usability of that component with an easier API that hides the details of a more complex one
  • We make it easier to mock and thus improve testability in our code
  • Being more loosely coupled makes it easy to replace that facaded component in case we want to use a new technology

Take for instance our LocationManager class. As pointed before, we want to simplify and hide the complexity of Apple’s CLLocationManager, that is implemented through the delegation pattern via the CLLocationManagerDelegate protocol.

To be simpler, we obtain the user location at a given moment just once, without the need to keep listening to location changes.

In spite of this, we do not hold anything against the delegate pattern per se; we take it as another powerful tool in our toolset that might be very useful for the right case.

Coming back to our case, it is essential to remark that because we need the location just once (fire and forget), we can convert our API to async/await, same way as before we used promises.

If it was required to be updated on any of the user location changes we would still have to use some sort of reactive programming paradigm as Combine or RxSwift, because there is a continuous flow to observe.

Swift Concurrency Evolution

The git history of the LocationManager file is a very interesting source to track the evolution of concurrency in Swift and our team.

After a brief period of using the raw Delegate Apple API, we started facading it by using callbacks, passing the new location to the client through a closure.

After that we discovered the power of Promises and created our own light Promises Open Source library to implement them, Pied Piper. (Again, if there was the need of being updated continuously we would have used a more Reactive approach).

Then Combine arrived, and we replaced that third-party Promises library with the Combine’s counterparts. And finally, the time has come, allegedly to stay for very long, when that returned Publisher can be kicked out and replaced by the await keyword.

The evolution of Swift Asynchronous Code in WELT iOS for the Location Manager
The evolution of Swift Asynchronous Code in WELT iOS for the Location Manager

The Combine Facade

As expressed, the last version of our LocationManager before async/await is implemented with the help of Combine’s Publishers and Promises:

import Combine
import CoreLocation

public typealias Location = CLLocationCoordinate2D

final class LocationManager: NSObject {
  fileprivate lazy var locationManager = CLLocationManager()
  fileprivate var locationStatus = CLAuthorizationStatus.notDetermined

  fileprivate var locationPromise: ((Result<Location, Error>) -> Void)?

  func updateLocation() -> AnyPublisher<Location, Error> {
    Future { [weak self] promise in
      guard let self = self else {
        return
      }

      self.locationManager.delegate = self
      self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
      self.locationManager.requestWhenInUseAuthorization()
      self.locationManager.startUpdatingLocation()

      self.locationPromise = promise

    }.eraseToAnyPublisher()
  }
}

extension LocationManager: CLLocationManagerDelegate {
  func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let locationObj = locations.last {
      let coord = locationObj.coordinate
      let location = Location(latitude: coord.latitude, longitude: coord.longitude)
      locationPromise?(.success(location))
    }
  }

  func locationManager(_: CLLocationManager, didFailWithError error: Error) {
    locationPromise?(.failure(error))
  }
}

As you can see, with the help of a promise instance property we are able to let this class client when the location is obtained, by retaining the returned publisher and reacting when updated:

final class LocationManagerClient {
  private let locationManager = LocationManager()
  private var cancellable: AnyCancellable?

  func listenToLocationUpdates() {
    cancellable = locationManager.updateLocation().sink(receiveCompletion: { _ in },
                                                        receiveValue: { location in
      // Do something with the location
    })
  }
}

From Combine to async/await with Continuations

That approach fulfilled the goals we had in mind when creating a facade: it hides Apple’s CoreLocation implementation details and provides an easier API to deal with.

But in our insatiable desire for improvement, we realised that that API can still be simpler and more readable by converting it to async/await. How can we bridge the CoreLocation asynchronous delegate pattern to it? With the help of our new friend, the Checked Continuation.

In a similar fashion to the way we return a publisher that will be updated afterward via the promise property, we will now use a checked continuation to keep the program state when the updateLocation is called, to continue once the location is retrieved:

import CoreLocation

public typealias Location = CLLocationCoordinate2D

enum LocationError: Error {
  case requestInProgress
}

final class LocationManager: NSObject {
  private typealias LocationCheckedThrowingContinuation = CheckedContinuation<Location, Error>

  private lazy var locationManager = CLLocationManager()

  private var locationCheckedThrowingContinuation: LocationCheckedThrowingContinuation?

  func updateLocation() async throws -> Location {
    // One request at a time: a second call would overwrite the stored continuation
    // and leave the first caller waiting forever.
    guard locationCheckedThrowingContinuation == nil else {
      throw LocationError.requestInProgress
    }

    return try await withCheckedThrowingContinuation { (continuation: LocationCheckedThrowingContinuation) in
      self.locationCheckedThrowingContinuation = continuation

      self.locationManager.delegate = self
      self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
      self.locationManager.requestWhenInUseAuthorization()
      self.locationManager.startUpdatingLocation()
    }
  }

  private func finish(with result: Result<Location, Error>) {
    // We need the location just once, so stop updating and resume a single time.
    locationManager.stopUpdatingLocation()
    locationCheckedThrowingContinuation?.resume(with: result)
    locationCheckedThrowingContinuation = nil
  }
}

extension LocationManager: CLLocationManagerDelegate {
  func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let coordinate = locations.last?.coordinate {
      finish(with: .success(coordinate))
    }
  }

  func locationManager(_: CLLocationManager, didFailWithError error: Error) {
    finish(with: .failure(error))
  }
}

Here we:

  • Create a typealias for our continuation type to make it more readable along with our class
  • Keep the location continuation in a property of that type
  • When the location is requested we start a continuation asking the CLLocationManager to update the location. That continuation reference is kept with our property so it can be resumed with the right value when that is obtained. (Or with an error)
  • In that manner, when we get the Core Location delegate callback with the updated location we resume our continuation with that value. That resumes the execution of the original function. If instead, we get an error, we resume it throwing it.

That way, the code to call our manager is much simpler:

final class LocationManagerClient {
  private let locationManager = LocationManager()

  func listenToLocationUpdates() async throws {
    let location = try await locationManager.updateLocation()

    // Do something with the location
  }
}

Note how easy and clean is the call to obtain the location now, thanks to the new async/await syntax.

It is important to note that the continuation should be called to resume just once.

If we do not resume it the function client will be waiting forever holding the resources indefinitely

If we do it more than once “ala Reactive flow” your app will crash. No alternatives here.

Therefore, we have to be especially careful to dodge these calamities. In our case we avoid it by:

  • Resuming the Continuation when CoreLocation returned an error. That way we are sure that it will be resumed at least once.
  • Setting the continuation to nil right after it is resumed. That way we are sure that it won’t be called more than once. If the location is required again it will be recreated.
  • Refusing a second request while one is still waiting. Otherwise the new continuation would replace the stored one, and the first caller would never be resumed.
  • Stopping location updates once we resume, since we only need one location.

Checked or Unsafe?

Apple provides two types of continuations to be used: checked, and unsafe. As their name indicates, from the documentation:

CheckedContinuation performs runtime checks for missing or multiple resume operations. UnsafeContinuation avoids enforcing these invariants at runtime because it aims to be a low-overhead mechanism for interfacing Swift tasks with event loops, delegate methods, callbacks, and other non-async scheduling mechanisms. However, during development, the ability to verify that the invariants are being upheld in testing is important. Because both types have the same interface, you can replace one with the other in most circumstances, without making other changes.

Therefore, if you want to use unsafe Continuations you have to:

  • Be sure that your Continuation will always resume
  • Profile your app to verify that the extra checks that come along with Checked Continuations caused some performance degradation

If any of these points are not true for you I suggest staying in the safe territory using Checked Continuations, given the cost of having missing or multiple resume operations.

Recapping

In this article, we acknowledged the role of Continuations within the new Swift Concurrency Model, and why it can be relevant for us.

After briefly reviewing how Facades are crucial to achieving clean code and the history of concurrency in our application, we went forward to migrate our Core Location Facade from Combine Promises to an async syntax API with the help of Continuations.

Next, we stated the consequences of not resuming our Continuation or making it more than once, and when to opt for Unsafe Continuations instead of Checked ones.

I hope you now have Continuations as another powerful tool in your toolbox, ready to be used when migrating from Callbacks or Delegate patterns to async/await. If you have questions, remarks or suggestions let me know.

Happy coding!!

César Vargas Casaseca is a Mobile Engineer at Automattic. He writes about Swift, iOS and app architecture. More about me.

Keep reading

Leave a Reply

Your email address will not be published. Required fields are marked *