Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do async calls within a function marked with @MainActor also run on the main thread?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading