I try to build Table with Observation framework but Table doesn't track changes in data. However, the List keeps track.
@Observable
final class Item: Identifiable {
var id: UUID
var value: Int
init(value: Int) {
self.id = UUID()
self.value = value
}
}
@Observable
final class AppModel {
var items: [Item]
init() {
var items: [Item] = []
for i in 0...10 {
items.append(Item(value: i))
}
self.items = items
}
func updateValue() {
let index = Int.random(in: 0..<items.count)
items[index].value = Int.random(in: 200...300)
}
func startTimer() {
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
self.updateValue()
}
}
}
@main
struct TestApp: App {
@State private var appModel = AppModel()
var body: some Scene {
WindowGroup {
ContentView()
.environment(appModel)
}
}
}
struct ContentView: View {
@Environment(AppModel.self) private var appModel
var body: some View {
VStack {
Table(appModel.items) {
TableColumn("Value") {
Text("\($0.value)")
}
}
List(appModel.items) {
Text("\($0.value)")
}
}
.padding()
.frame(minHeight: 640)
.onAppear {
appModel.startTimer()
}
}
}
What am I missing? Thank you.