swiftbindingstatecombinepublisher

How to attach subscriber to State or Binding in SwiftUI/Combine?


With a Combine Publisher, I can use the following to call a closure whenever a value changes:

let cancellable = x.sink { value in … }

How can I achieve the same behaviour with a variable marked @State or @Binding?


Solution

  • You can use .onChange(of:) instead on the property

    .onChange(of: someProperty) { value in
        //use new value for someProperty
     }
    

    or from iOS 17, macOS 14 etc the new onChange

    .onChange(of: someProperty) { _, value in
        //use new value for someProperty
     }