简体   繁体   English

在 ObservableObject 中观察多个已发布的变量变化

[英]Observing multiple published variable changes inside ObservableObject

I have an ObservableObject that contains multiple published variables to handle my app state.我有一个ObservableObject ,它包含多个已发布的变量来处理我的应用程序状态。 Whenever one of those published variables change, I want to call a function inside my ObservableObject .每当这些已发布的变量之一发生变化时,我都想在我的ObservableObject调用一个函数。 What's the best way to do that?最好的方法是什么?

class AppModelController: ObservableObject {

    @Published var a: String = "R"
    @Published var b: CGFloat = 0.0
    @Published var c: CGFloat = 0.9
    
    // Call this function whenever a, b or c change
    func check() -> Bool {

    }
}

You can use didSet, like this code:你可以使用 didSet,像这样的代码:

class AppModelController: ObservableObject {

    @Published var a: String = "R" { didSet(oldValue) { if (a != oldValue) { check() } } }
    @Published var b: CGFloat = 0.0 { didSet(oldValue) { if (b != oldValue) { check() } } }
    @Published var c: CGFloat = 0.9 { didSet(oldValue) { if (c != oldValue) { check() } } }
    

    func check() {
        
        // Some Work!

    }
}

The simplest thing you can do is listen to objectWillChange .您可以做的最简单的事情就是听objectWillChange The catch is that it gets called before the object updates.问题是它在对象更新之前被调用。 You can use .receive(on: RunLoop.main) to get the updates on the next loop, which will reflect the changed values:您可以使用.receive(on: RunLoop.main)获取下一个循环的更新,这将反映更改的值:

import Combine

class AppModelController: ObservableObject {

    @Published var a: String = "R"
    @Published var b: CGFloat = 0.0
    @Published var c: CGFloat = 0.9
    
    private var cancellable : AnyCancellable?
    
    init() {
        cancellable = self.objectWillChange
        .receive(on: RunLoop.main)
        .sink { newValue in
            let _ = self.check()
        }
    }
    
    // Call this function whenever a, b or c change
    func check() -> Bool {
        return true
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM