How to tell SwiftUI views to bind to more than one nested ObservableObject

后端 未结 1 1233
轮回少年
轮回少年 2021-02-04 09:04

I have two classes nested in another class, which is an observable object in a SwiftUI view. Even though properties in the nested classes are declared as @Published, their value

1条回答
  •  情书的邮戳
    2021-02-04 09:32

    You can expand upon the answer in the question you linked to by using CombineLatest to have your model fire its objectWillChange publisher when either of the underlying objects change:

    import Combine
    
    class Model: ObservableObject {
        @Published var submodel1: Submodel1 = Submodel1()
        @Published var submodel2: Submodel2 = Submodel2()
    
        var anyCancellable: AnyCancellable? = nil
    
        init() {
            anyCancellable = Publishers.CombineLatest(submodel1.$count,submodel2.$count).sink(receiveValue: {_ in
                self.objectWillChange.send()
            })
        }
    }
    

    0 讨论(0)
提交回复
热议问题