🎉 End-of-year Sale! Save 25% when you subscribe today.

How should you perform async work in a non-async context?

Episode Clip • Jun 4, 2024

We often need to perform async work when there is no async context, such as in SwiftUI button action closures. In such cases it seems that you have no choice but to spin up an unstructured Task, but you may have heard that doing so it bad. So what are you to do?

You will want to spin up unstructured Tasks in places that are already unstructured, such as in action closures of SwiftUI views. You should avoid creating Tasks inside observable models, where it is possibel to maintain structured programming by marking methods as async.

An exception to this rule is when your observable model needs later access to the unit of async work being performed. In that case you can create a Task in the model to store in a variable, but you should further also await the task immediately after its creation.

This is an excerpt from our episode “Reliable Async Tests: The Problem”.

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 64 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing