Home > Blockchain >  Captured value within completion handler not mutating
Captured value within completion handler not mutating

Time:03-20

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
    }

CodePudding user response:

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.

CodePudding user response:

vadian is right but it's better-expressed as a computed property nowadays.

var allPeople: [PersonModelProtocol] {
  get async throws {
    try JSONDecoder().decode(
      [Person].self,
      from: await session.data(for: request!).0
    )
  }
}

And also, your code does mutate people, but returning its empty value before it gets mutated.

  • Related