ios – Updating a @State var in SwiftUI from an async method doesn’t work

0
36

[ad_1]

I have the following View:

struct ContentView: View {
    @State var data = [SomeClass]()

    var body: some View {
        List(data, id: \.self) { item in
            Text(item.someText)
        }
    }

    func fetchDataSync() {
        Task.detached {
            await fetchData()
        }
    }

    @MainActor
    func fetchData() async {
        let data = await SomeService.getAll()
        self.data = data
        print(data.first?.someProperty)
        // > Optional(115)
        print(self.data.first?.someProperty)
        // > Optional(101)
    }
}

now the method fetchDataSync is a delegate that gets called in a sync context whenever there is new data. I’ve noticed that the views don’t change so I’ve added the printouts. You can see the printed values, which differ. How is this possible? I’m in a MainActor, and I even tried detaching the task. Didn’t help. Is this a bug?

It should be mentioned that the objects returned by getAll are created inside that method and not given to any other part of the code. Since they are class objects, the value might be changed from elsewhere, but if so both references should still be the same and not produce different output.

My theory is that for some reason the state just stays unchanged. Am I doing something wrong?

[ad_2]