swiftcombineobservableobjectproperty-wrapper-published

Can I omit `ObservableObject` conformance?


Apple's documentation pretty much only says this about ObservableObject: "A type of object with a publisher that emits before the object has changed. By default an ObservableObject synthesizes an objectWillChange publisher that emits the changed value before any of its @Published properties changes.".

And this sample seems to behave the same way, with or without conformance to the protocol by Contact:

import UIKit
import Combine

class ViewController: UIViewController {
    let john = Contact(name: "John Appleseed", age: 24)
    
    private var cancellables: Set<AnyCancellable> = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        john.$age.sink { age in
            print("View controller's john's age is now \(age)")
        }
        .store(in: &cancellables)
        print(john.haveBirthday())
    }


}

class Contact {
    @Published var name: String
    @Published var age: Int


    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }


    func haveBirthday() -> Int {
        age += 1
        return age
    }
}

Can I therefore omit conformance to ObservableObject every time I don't need the objectWillChange publisher?


Solution

  • You only need the ObservableObject conformance if you need a SwiftUI view to be auto-updated when an @Published property of your object changes. You also need to store the object as @ObservedObject or @StateObject to get the auto-updating behaviour and these property wrappers actually require the ObservableObject conformance.

    As you're using UIKit and hence don't actually get any automatic view updates, you don't need the ObservableObject conformance.