Some articles say that the @State variable has to be updated in main thread. But I did some tests and found it is ok to update @State variable in background thread. This is my code:
import SwiftUI
@Observable
class ViewModel {
var name = "old name"
}
struct ContentView: View {
@State var viewModel = ViewModel()
@State var title = "old title"
var body: some View {
VStack {
Text(viewModel.name)
Text(title)
}
.onAppear {
Task.detached {
viewModel.name = "new name"
title = "new title"
}
}
}
}
#Preview {
ContentView()
}
I wonder if it is correct to update @State variable in background thread ? What’s the drawback of doing so? Thanks.