swiftasync-awaitconcurrencyios15mainactor

How to use URLSession in MainActor


I have a ViewModel that is isolated with @MainActor and I assume that every part of this ViewModel class should run on the main actor (main thread), right?

So the question is, what about the async call of URLSession.shared.data?

Does it also run on main thread? Isn't that a bad approach?

@MainActor
class ViewModel {
    @Published var name: String = ""
    
    func fetchName() async {
        guard let (data, _) = try? await URLSession.shared.data(from: URL(string: "http://....")!),
              let response = try? JSONDecoder().decode(Response.self, from: data) else {
            return
        }
        
        self.name = response.name
    }
}

Solution

  • Does it also run on main thread

    No. That's the whole point of saying await. At that moment, the system can switch contexts to a background thread without you knowing or caring. Moreover, at await your code pauses without blocking — meaning that while you're waiting for the download, the main thread is free to do other work, the user can interact with your app, etc. Don't worry be happy.