The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech LeadsJuly 17-18

Join

Concurrency Extras

CI Slack

Reliably testable Swift concurrency.

Learn more

This library was designed to support libraries and episodes produced for Point-Free, a video series exploring the Swift programming language hosted by Brandon Williams and Stephen Celis.

You can watch all of the episodes here.

video poster image

Motivation

This library comes with a number of tools that make working with Swift concurrency easier and more testable.

LockIsolated

The LockIsolated type helps wrap other values in an isolated context. It wraps the value in a class with a lock, which allows you to read and write the value with a synchronous interface.

AnyHashableSendable

The AnyHashableSendable type is a type-erased wrapper like AnyHashable that preserves the sendability of the underlying value.

Streams

The library comes with numerous helper APIs spread across the two Swift stream types:

Tasks

The library enhances the Task type with new functionality.

Serial execution

Some asynchronous code is notoriously difficult to test in Swift due to how suspension points are processed by the runtime. The library comes with a static function, withMainSerialExecutor, that attempts to run all tasks spawned in an operation serially and deterministically. This function can be used to make asynchronous tests faster and less flakey.

Warning: This API is only intended to be used from tests to make them more reliable. Please do not use it from application code.

We say that it "attempts to run all tasks spawned in an operation serially and deterministically" because under the hood it relies on a global, mutable variable in the Swift runtime to do its job, and there are no scoping guarantees should this mutable variable change during the operation.

For example, consider the following seemingly simple model that makes a network request and manages some isLoading state while the request is inflight:

@Observable
class NumberFactModel {
  var fact: String?
  var isLoading = false
  var number = 0

  // Inject the request dependency explicitly to make it testable, but can also
  // be provided via a dependency management library.
  let getFact: (Int) async throws -> String

  func getFactButtonTapped() async {
    self.isLoading = true
    defer { self.isLoading = false }
    do {
      self.fact = try await self.getFact(self.number)
    } catch {
      // TODO: Handle error
    }
  }
}

We would love to be able to write a test that allows us to confirm that the isLoading state flips to true and then false. You might hope that it is as easy as this:

func testIsLoading() async {
  let model = NumberFactModel(getFact: { 
    "\($0) is a good number." 
  })

  let task = Task { await model.getFactButtonTapped() }
  XCTAssertEqual(model.isLoading, true)
  XCTAssertEqual(model.fact, nil)

  await task.value
  XCTAssertEqual(model.isLoading, false)
  XCTAssertEqual(model.fact, "0 is a good number.")
}

However this fails almost 100% of the time. The problem is that the line immediately after creating the unstructured Task executes before the line inside the unstructured task, and so we never detect the moment the isLoading state flips to true.

You might hope you can wiggle yourself in between the moment the getFactButtonTapped method is called and the moment the request finishes by using a Task.yield:

 func testIsLoading() async {
   let model = NumberFactModel(getFact: { 
     "\($0) is a good number." 
   })

   let task = Task { await model.getFactButtonTapped() }
+  await Task.yield()
   XCTAssertEqual(model.isLoading, true)
   XCTAssertEqual(model.fact, nil)

   await task.value
   XCTAssertEqual(model.isLoading, false)
   XCTAssertEqual(model.fact, "0 is a good number.")
 }

But that still fails the vast majority of times.

These problems, and more, can be fixed by running this entire test on the main serial executor. You will also have insert a small yield in the getFact endpoint due to Swift's ability to inline async closures that do not actually perform async work:

 func testIsLoading() async {
+  await withMainSerialExecutor {
     let model = NumberFactModel(getFact: {
+      await Task.yield()
       return "\($0) is a good number." 
     })

     let task = Task { await model.getFactButtonTapped() }
     await Task.yield()
     XCTAssertEqual(model.isLoading, true)
     XCTAssertEqual(model.fact, nil)

     await task.value
     XCTAssertEqual(model.isLoading, false)
     XCTAssertEqual(model.fact, "0 is a good number.")
+  }
 }

That small change makes this test pass deterministically, 100% of the time.

Documentation

The latest documentation for this library is available here.

Credits and thanks

Thanks to Pat Brown and Thomas Grapperon for providing feedback on the library before its release. Special thanks to Kabir Oberai who helped us work around an Xcode bug and ship serial execution tools with the library.

Other libraries

Concurrency Extras is just one library that makes it easier to write testable code in Swift.

License

This library is released under the MIT license. See LICENSE for details.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.