Using JSONDecoder on a background thread in Swift 5.5+

Viewed 279

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)
}
2 Answers

The decode task will, as Joshua said, run on a thread of the discretion of the new concurrency system (including the main thread). When you initiate a new task, it may start on the current thread or it may start on another thread(s) taken from the cooperative thread pool. Furthermore, Swift may run the continuation code (the code after the await) on yet another thread from the cooperative thread pool (see WWDC 2021 video Swift concurrency: Behind the scenes).

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.

Related