[SOLVED] Captured value within completion handler not mutating

Issue

So I have here an async method defined on an actor type. The issue im having is that people isnt being mutated at all; mainly due to what from what I understand concurrency issues. From what I think I know the completion handler is executed concurrently on the same thread and so cannot mutate people.

Nonetheless my knowledge in this area is pretty foggy, so any suggestions to solve it and maybe a better explanation as to why this is happening would be great! Ive thought of a few things but im still new to concurrency.

func getAllPeople() async -> [PersonModelProtocol] { 
        
        let decoder = JSONDecoder()
        var people: [Person] = []
        
        let dataTask = session.dataTask(with: request!) { data, response, error in
            do {
                let newPeople = try! decoder.decode([Person].self, from: data!)
                people = newPeople
            } catch {
                print(error)
            }
        }
        dataTask.resume()
        return people
    }

Solution

If you do want to use async/await you have to use the appropriate API.

func getAllPeople() async throws -> [Person] { 
    let (data, _ ) = try await session.data(for: request!)
    return try JSONDecoder().decode([Person].self, from: data)
}

In a synchronous context you cannot return data from a completion handler anyway.

Answered By – vadian

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.