Skip to content

Commit 87277a8

Browse files
committed
Add state playgrounds (State, Environment, Observable)
1 parent f1245ac commit 87277a8

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#if canImport(AndroidSwiftUI)
2+
import AndroidSwiftUI
3+
#else
4+
import SwiftUI
5+
#endif
6+
7+
import Observation
8+
9+
struct StatePlayground: View {
10+
@State private var parentRenders = 0
11+
var body: some View {
12+
ScrollView {
13+
VStack(alignment: .leading, spacing: 0) {
14+
Example("Parent re-renders: \(parentRenders)") {
15+
Button("Re-render parent") { parentRenders += 1 }
16+
}
17+
Example("Child keeps its own state") {
18+
StateChild()
19+
}
20+
}
21+
}
22+
}
23+
}
24+
25+
struct StateChild: View {
26+
@State private var localCount = 0
27+
var body: some View {
28+
VStack(alignment: .leading, spacing: 8) {
29+
Text("Local count: \(localCount)")
30+
Button("Bump child") { localCount += 1 }
31+
Text("Survives parent re-renders")
32+
}
33+
}
34+
}
35+
36+
@Observable
37+
final class CounterModel {
38+
var value = 0
39+
}
40+
41+
struct EnvironmentPlayground: View {
42+
@State private var model = CounterModel()
43+
var body: some View {
44+
ScrollView {
45+
VStack(alignment: .leading, spacing: 0) {
46+
Example("Injected object") {
47+
EnvReader().environment(model)
48+
}
49+
Example("Read here too") {
50+
EnvReader().environment(model)
51+
}
52+
}
53+
}
54+
}
55+
}
56+
57+
struct EnvReader: View {
58+
@Environment(CounterModel.self) private var model
59+
var body: some View {
60+
VStack(alignment: .leading, spacing: 8) {
61+
Text("Shared value: \(model.value)")
62+
Button("Increment shared") { model.value += 1 }
63+
}
64+
}
65+
}
66+
67+
struct ObservablePlayground: View {
68+
@State private var model = CounterModel()
69+
var body: some View {
70+
ScrollView {
71+
VStack(alignment: .leading, spacing: 0) {
72+
Example("Observation drives updates") {
73+
VStack(alignment: .leading, spacing: 8) {
74+
Text("Observable value: \(model.value)")
75+
Button("Increment") { model.value += 1 }
76+
Text("Mutating the model re-evaluates automatically")
77+
}
78+
}
79+
}
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)