Post

Replies

Boosts

Views

Activity

Reply to Observation and MainActor
Now that @Observable macro has been out a little bit, what's the latest thinking on this? 🤔 How would one apply @MainActor to the ViewModel of the following code? Currently, doing so gives the "Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context" error on the @State line in the TestApp struct. import SwiftUI @main struct TestApp: App { @State private var vm = ViewModel() var body: some Scene { WindowGroup { ContentView() .environment(vm) } } } @Observable @MainActor class ViewModel { var showDetails: Bool = false } struct ContentView: View { @Environment(ViewModel.self) var vm var body: some View { @Bindable var vm = vm VStack { DetailsButton(showDetails: $vm.showDetails) if vm.showDetails { Text("This is my message!") } } } } struct DetailsButton: View { @Binding var showDetails: Bool var body: some View { Button("\(showDetails ? "Hide" : "Show") Details") { showDetails.toggle() } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Nov ’23