I have an ObservableObject
class and a SwiftUI view. When a button is tapped, I create a Task
and call populate
(an async function) from within it. I thought this would execute populate
on a background thread but instead the entire UI freezes. Here’s my code:
class ViewModel: ObservableObject {
@Published var items = [String]()
func populate() async {
var items = [String]()
for i in 0 ..< 4_000_000 { /// this usually takes a couple seconds
items.append("(i)")
}
self.items = items
}
}
struct ContentView: View {
@StateObject var model = ViewModel()
@State var rotation = CGFloat(0)
var body: some View {
Button {
Task {
await model.populate()
}
} label: {
Color.blue
.frame(width: 300, height: 80)
.overlay(
Text("(model.items.count)")
.foregroundColor(.white)
)
.rotationEffect(.degrees(rotation))
}
.onAppear { /// should be a continuous rotation effect
withAnimation(.easeInOut(duration: 2).repeatForever()) {
rotation = 90
}
}
}
}
Result:
The button stops moving, then suddenly snaps back when populate
finishes.
Weirdly, if I move the Task
into populate
itself and get rid of the async
, the rotation animation doesn’t stutter so I think the loop actually got executed in the background. However I now get a Publishing changes from background threads is not allowed
warning.
func populate() {
Task {
var items = [String]()
for i in 0 ..< 4_000_000 {
items.append("(i)")
}
self.items = items /// Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
}
}
/// ...
Button {
model.populate()
}
Result:
How can I ensure my code gets executed on a background thread? I think this might have something to do with MainActor
but I’m not sure.
5
Answers
Update 6/10/22: At WWDC I asked some Apple engineers about this problem — it really is all about actor inheritance. However, there were some compiler-level changes in Xcode 14 Beta. For example, this will run smoothly on Xcode 14, but lag on Xcode 13:
Again,
Task
inherits the context of where it's called.Task
called from within a plainObservableObject
class will run in the background, since the class isn't a main actor.Task
called inside aButton
will probably run on the main actor, since theButton
is a UI element. Except, Xcode 14 changed some things and it actually runs in the background too...To make sure a function runs on the background thread, independent of the inherited actor context, you can add
nonisolated
.Note: the Visualize and optimize Swift concurrency video is super helpful.
You can fix it by removing the class. You aren’t using Combine so you don’t need its
ObservableObject
and SwiftUI is most efficient if you stick to value types. The button doesn’t hang with this design:First, you can’t have it both ways; Either you perform your CPU intensive work on the main thread (and have a negative impact on the UI) or you perform the work on another thread, but you need to explicitly dispatch the UI update onto the main thread.
However, what you are really asking about is
When you use a
Task
you are using unstructured concurrency, and when you initialise yourTask
via init(priority:operation) the task … inherits the priority and actor context of the caller.While the
Task
is executed asynchronously, it does so using the actor context of the caller, which in the context of aView
body
is the main actor. This means that while your task is executed asynchronously, it still runs on the main thread and that thread is not available for UI updates while it is processing. So you are correct, this has everything to do withMainActor
.When you move the
Task
intopopulate
it is no longer being created in aMainActor
context and therefore does not execute on the main thread.As you have discovered, you need to use this second approach to avoid the main thread. All you need to do to your code is move the final update back to the main queue using the
MainActor
:You could also use
Task.detached()
in the body context to create aTask
that is not attached theMainActor
context.Consider:
You have marked
populate
withasync
, but there is nothing asynchronous here, and it will block the calling thread.Then consider:
That looks like it must be asynchronous, since it is launching a
Task
. But thisTask
runs on the same actor, and because the task is slow and synchronous, it will block the current executor.If you do not want it to run on the main actor, you can either:
You can leave the view model on the main actor, but manually move the slow synchronous process to a detached task:
For the sake of completeness, you could also make the view model to be its own actor, and only designate the relevant observed properties as being on the main actor:
I would generally lean towards the former, but both approaches work.
Either way, it will allow the slow process to not block the main thread. Here I tapped on the button twice:
See WWDC 2021 videos Swift concurrency: Behind the scenes, Protect mutable state with Swift actors, and Swift concurrency: Update a sample app, all of which are useful when trying to grok the transition from GCD to Swift concurrency.
As others have mentioned, the reason of this behavior is that the
Task.init
inherits the actor context automatically. You’re calling your function from the button callback:The button callback is on the main actor, so the closure passed to the
Task
initializer is on the main actor too.One solution is using a detached task:
While detached tasks are unstructured, I’d like to suggest structured tasks like
async let
tasks:This is useful when you want the
populate
function to return some value asynchronously. This structured task approach also means cancellation can be propagated automatically. For example, if you want to cancel the calculation when the button is tapped multiple times in a short time, you can do something like this:Moreover,
withTaskGroup
also creates structured tasks and you can avoid inheriting the actor context too. It can be useful when your computation has multiple child tasks that can progress concurrently.