@Observable in SwiftUI

2 min readSep 14, 2024

The @Observable macro, introduced at WWDC 2023 and supported from iOS17 onwards, it replaces ObservableObject and @Published properties. It automatically triggers SwiftUI view updates when any changes occurs.

Let’s move to the code

Before @Observable macro

// View
struct ContentView: View {
@StateObject var vm: ViewModel = ViewModel()
var body: some View {
VStack {
Text("Hello, world \(vm.count)")
Button {
vm.count += 1
} label: {
Text("Click me")
}
}
.padding()
}
}
// Viewmodel
final class ViewModel: ObservableObject {
@Published var count: Int = 0
}

After implementing @Observable macro

// View
struct ContentView: View {
let vm: ViewModel = ViewModel()
var body: some View {
VStack {
Text("Hello, world \(vm.count)")
Button {
vm.count += 1
} label: {
Text("Click me")
}
}
.padding()
}
}
// Viewmodel
@Observable
final class ViewModel {
var count: Int = 0
}

Let see the output

Simple and easy right???? 😉

If you right click @Observable macro and click on Refactor->Inline Macro then you see below code.

final class ViewModel {
@ObservationTracked var count: Int = 0


@ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar()

internal nonisolated func access<Member>(
keyPath: KeyPath<ViewModel , Member>
) {
_$observationRegistrar.access(self, keyPath: keyPath)
}

internal nonisolated func withMutation<Member, MutationResult>(
keyPath: KeyPath<ViewModel , Member>,
_ mutation: () throws -> MutationResult
) rethrows -> MutationResult {
try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
}

extension ViewModel: Observation.Observable {
}

Please like and follow for more

Thanks for reading, Happy Coding 💻

--

--

No responses yet