Post

Replies

Boosts

Views

Activity

@MainActor and the guarantee that the properties are only ever accessed from the main actor
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?
0
0
1.4k
Jan ’22
@MainActor and the guarantee that the properties are only ever accessed from the main actor
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?
Replies
0
Boosts
0
Views
1.4k
Activity
Jan ’22