Skip to content

Instantly share code, notes, and snippets.

@landonepps
Created June 8, 2023 18:51
Show Gist options
  • Save landonepps/011274ab2b2cfa08710172e967470a0e to your computer and use it in GitHub Desktop.
Save landonepps/011274ab2b2cfa08710172e967470a0e to your computer and use it in GitHub Desktop.
How @ObservationTracked could work
import SwiftUI
import Observation
class User {
var id: Int {
get {
access(keyPath: \.id)
return _id
}
set {
withMutation(keyPath: \.id) {
_id = newValue
}
}
}
@ObservationIgnored private let _$observationRegistrar = ObservationRegistrar()
internal nonisolated func access<Member>(
keyPath: KeyPath<User , Member>
) {
_$observationRegistrar.access(self, keyPath: keyPath)
}
internal nonisolated func withMutation<Member, T>(
keyPath: KeyPath<User , Member>,
_ mutation: () throws -> T
) rethrows -> T {
try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
@ObservationIgnored private lazy var _id: Int = {
return Int.random(in: 1...100)
}()
}
extension User : Observable {}
struct ContentView: View {
let user = User()
var body: some View {
VStack {
Text("User ID: \(user.id)")
Button("Randomize ID") {
user.id = Int.random(in: 1...100)
}
}
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment