Created
June 8, 2023 18:51
-
-
Save landonepps/011274ab2b2cfa08710172e967470a0e to your computer and use it in GitHub Desktop.
How @ObservationTracked could work
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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