Subscribing to changes to @Published

假装没事ソ 提交于 2020-02-05 02:37:27

问题


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.


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/59573754/subscribing-to-changes-to-published

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!