Junior — Middle
Can you explain the principle of how ObservableObject works and its role in reactive programming?
sobes.tech AI
Answer from AI
ObservableObject is a protocol in SwiftUI that allows an object to notify its subscribers about changes to its data. It is a key element of reactive programming, where the UI automatically updates when the model's state changes.
When a class conforms to ObservableObject and marks its properties with @Published, any changes to these properties trigger notifications, and the associated SwiftUI views update accordingly.
Example:
import SwiftUI
import Combine
class UserSettings: ObservableObject {
@Published var username: String = ""
}
struct ContentView: View {
@ObservedObject var settings = UserSettings()
var body: some View {
TextField("Username", text: $settings.username)
Text("Hello, \(settings.username)!")
}
}
Here, when the username changes, the text in the interface automatically updates. Thus, ObservableObject links the model and the view, ensuring reactive UI updates.