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?

@Filippo02

Yes it fine, both ObservableObject and @Published are defined within the Combine framework, and so provide Combine functionality.

You should consider whether using Observable might be a better option for your use case as it doesn't rely on any publishers or subjects at all.

@DTS Engineer Hello,

Thank you for your reply.

I feel like the following is a better answer, since it gives some explanation: "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."

Credit: https://stackoverflow.com/a/78812534/22697469.

As per your suggestion to use the @Observable macro, unfortunately, I can't target just iOS 17 or above.

Can I omit `ObservableObject` conformance?
 
 
Q