Posts

Post not yet marked as solved
0 Replies
429 Views
In https://developer.apple.com/videos/play/wwdc2021-10019/?time=815 was said: "By adding the new @MainActor annotation to Photos, the compiler will guarantee that the properties (...) are only ever accessed from the main actor." What does it exactly mean? Let's consider the following example: @MainActor class ViewModel: ObservableObject {   @Published var text = "" } struct ContentView: View {   @StateObject private var viewModel = ViewModel()   var body: some View {     VStack {       Text(viewModel.text)         .padding()       Button("Refresh") {         Task.detached {           await updateText()         }       }     }   }   func updateText() async {     viewModel.text = "Hello, world"   } } Compiler doesn't complain. After button tap viewModel.text is changed from background actor and there is runtime warning: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates." So once again: How exactly @MainActor annotation and the compiler will guarantee that the properties are only ever accessed from the main actor?
Posted
by Jan_k.
Last updated
.