🐡
[SwiftUI] Observable protocolを直接使う実験のメモ
SwiftUIでは@Observable macroが使うことでObservable protocolに準拠し、SwiftUI runtimeはそのobjectをobserveする
その中身はなんなのか
Observable protocolを直接使って何かに活用できるのか?
SwiftDataのmacroのexpansionを見て思った
- SwiftUIから見てviewのpropertyのtypeがObservable protocolを持っているか
- Observableの要求を満たすためにObservationRegistrarは別にいらないのか?
import Observation
import SwiftUI
final class Updater: Observable {
let f: ObservationRegistrar = .init()
func set() {
f.access(self, keyPath: \.self)
}
func up() {
f.withMutation(of: self, keyPath: \.self) {
}
}
}
private struct _Book: View {
let updater = Updater()
var body: some View {
let _ = print("render")
let _ = updater.set()
VStack {
Button("Update") {
updater.up()
}
}
}
}
#Preview("ViewUpdater") {
_Book()
}
一応こんな感じでviewのアップデートはトリガーできた
Discussion