Observing multiple published variable changes inside ObservableObject

Viewed 476

I have an ObservableObject that contains multiple published variables to handle my app state. Whenever one of those published variables change, I want to call a function inside my 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 {

    }
}
2 Answers

You can use didSet, like this code:

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. 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:

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