I have a function marked with @MainActor that makes an async call, then updates a @Published var that will subsequently update the UI. Is the async call blocking on the main thread, or is the updating of the published var the only thing that will be done on the main thread?
@Published var users: [User] = []
@MainActor
func getUsers() {
Task {
// Is the async call blocking on the main thread here?
users = await userRepository.getUsers()
}
}
In the above example, is users being updated on the main thread, while the async call happening on the UserRepository being done in the background? Or, is that async call also being run and blocking on the main thread?
>Solution :
The Task initialiser
Task(priority:operation:)
inherits the priority and actor context of the caller, so in your case, as the func is marked @MainActor, it will run on the main queue.
userRepository.getUsers() runs on another queue, then when it returns your func continues back on the main queue.
While it’s running the main queue isn’t blocked, the func itself is suspended.