Skip to content

Commit 702f00e

Browse files
committed
Demonstrate task cancellation on disappear
1 parent 5d4e29b commit 702f00e

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

Demo/App.swiftpm/Sources/InteractionPlaygrounds.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ struct InteractionPlayground: View {
1010
@State private var slider = 0.0
1111
@State private var sliderChanges = 0
1212
@State private var blocked = true
13+
@State private var ticking = false
14+
@State private var ticks = 0
1315
var body: some View {
1416
ScrollView {
1517
VStack(alignment: .leading, spacing: 0) {
@@ -35,6 +37,26 @@ struct InteractionPlayground: View {
3537
}
3638
.onChange(of: slider) { sliderChanges += 1 }
3739
}
40+
Example(".task (cancels on disappear)") {
41+
VStack(alignment: .leading, spacing: 8) {
42+
Text("Ticks: \(ticks)")
43+
Button(ticking ? "Hide (cancels task)" : "Show") { ticking.toggle() }
44+
if ticking {
45+
Text("Ticking every 0.5s while visible")
46+
.foregroundColor(.white)
47+
.padding()
48+
.background(Color.green)
49+
.cornerRadius(8)
50+
.task {
51+
while true {
52+
do { try await Task.sleep(nanoseconds: 500_000_000) }
53+
catch { break } // cancelled on disappear → stop
54+
ticks += 1
55+
}
56+
}
57+
}
58+
}
59+
}
3860
Example("disabled") {
3961
VStack(alignment: .leading, spacing: 8) {
4062
Button(blocked ? "Disabled button" : "Enabled button") { taps += 1 }

0 commit comments

Comments
 (0)