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 Task
s in places that are already unstructured, such as in action closures of SwiftUI views. You should avoid creating Task
s 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”.
👋 Hey there! If you got this far, then you must have enjoyed this post. You may want to also check out Point-Free, a video series covering advanced programming topics in Swift. Consider subscribing today!