Search code examples
iosswiftuicombine

Subscribing to changes to @Published


I am trying to bind the value of query to a search box sitting in a SwiftUI view.

class DataSet: ObservedObject {

... 

@Published var query: String = ""

init() {
    let sub = AnySubscriber<String, Never>(
        receiveSubscription: nil,
        receiveValue: { query in
            print(query)
            return .unlimited
        })
    self.$query.subscribe(sub)
}

...
}

When the user changes the value of the query I'd like to filter some other property in my ObservedObject. Yet I cannot find anywhere in the documentation how do I subscribe to changes to query property.


Solution

  • I would use the following approach

    class DataSet: ObservableObject {
        
        @Published var query: String = ""
        
        private var subscribers = Set<AnyCancellable>()
        init() {
            self.$query
                .sink { newQuery in
                        // do something here with newQuery
                }
                .store(in: &subscribers)
        }
    }