SwiftUI observed object do action when its property change

2.6k Views Asked by At

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

There are 2 best solutions below

1
On

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
        }
   }
}
0
On

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