The following URL session is performed asynchronously. But what about the JSON decoding step? Is that happening on the main thread?
func fetchFavorites() async throws -> [Int] {
let url = URL(string: "https://hws.dev/user-favorites.json")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([Int].self, from: data)
}
CodePudding user response:
You are calling decode(...)
from within your async fetchFavorites()
function. This means that all of the code within it is running on whatever thread(s) the Swift runtime decides is most efficient. In practice that probably won't be the main thread, but in theory it could sometimes be.
CodePudding user response:
No, the decode task will not happen on the main thread. All of the code in fetchFavorites
runs on thread(s) taken from the cooperative thread pool.
As a technical aside, in WWDC 2021 video Swift concurrency: Behind the scenes, they point out that the continuation (i.e., the decode task) may actually run on a different thread than was initially used by fetchFavorites
. But it will not run on the main thread.