There is a Model made with Actor. ButtonView changes variables in Model. ColorView displays colors differently depending on the model variable values.
But this example doesn't work. Because await keyword cannot be used in ViewModifier.
Is this problem solvable? What am I missing?
Thank you for reading.
actor ActorModel: ObservableObject {
static let shared = ActorModel()
private init() {}
@Published var isActive: Bool = false
func toggleActive() {
isActive.toggle()
}
}
struct ContentView: View {
var body: some View {
VStack {
ColorView()
ButtonView()
}
.padding()
}
}
struct ColorView: View {
@ObservedObject private var model = ActorModel.shared
var body: some View {
VStack {
Rectangle()
.foregroundStyle(await model.isActive ? .red : .blue) // <-- Problem!
.frame(width: 100, height: 100)
}
.padding()
}
}
struct ButtonView: View {
@ObservedObject private var model = ActorModel.shared
var body: some View {
VStack {
Button("Toggle Color") {
Task {
await model.toggleActive()
}
}
}
.padding()
}
}
If you must use an
actorthen you should do something like this:Although,
@Publishedattribute has no meaning here. As you won't be getting updates from ananctor.If you need to subscribe to updates then you'd try another approach: