소피it블로그

[Combine] ObservableObject 정리 본문

개발_iOS/iOS 기타

[Combine] ObservableObject 정리

sophie_l 2022. 8. 12. 19:46

https://developer.apple.com/documentation/combine/observableobject

 

Apple Developer Documentation

 

developer.apple.com

해당 객체가 변경되기 전에 publisher를 발행하는 객체

 

1. 선언

protocol ObservableObject : AnyObject

2. 개요

 

ObservableObject는 기본적으로 @Published 프라퍼티가 바뀌기 전 변경된 값을 발행하는 objectWillChange 퍼블리셔를 포함한다.

class Contact: ObservableObject {
    @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
    }
}

let john = Contact(name: "John Appleseed", age: 24)
cancellable = john.objectWillChange
    .sink { _ in
        print("\(john.age) will change")
}
print(john.haveBirthday())
// Prints "24 will change"
// Prints "25"