SwiftUI observed object do action when its property change

Viewed 1438

I have observed object which is created in view and I want to have function that will occur when the object bool property is changed. I want something similar to .onTapGesture. Is there a way to do it? have function where the body of the function is created outside of that object?

2 Answers

Let's replicate...

class Demo: ObservableObject {
   @Published var value = false
}

struct DemoView: View {
   @ObservedObject var demo = Demo()

   var body: some View {
      Text("Demo") 
        .onReceive(demo.$value) { flag in
            // call here your function
        }
   }
}

use @ObservedObject to make change in value an use @StateObject to read the published value

Related