Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created February 25, 2024 23:48
Show Gist options
  • Save hmlongco/c14a6c47a0ac77944396e254ab042653 to your computer and use it in GitHub Desktop.
Save hmlongco/c14a6c47a0ac77944396e254ab042653 to your computer and use it in GitHub Desktop.
Interrupting a Button
class InterruptedTaskViewModel: ObservableObject {
@Published var name = "Michael"
init() {
print("INIT")
}
@MainActor
func load() {
Task {
print("LOADING")
let _ = try? await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC)
print("LOADED")
name = "Nicholas"
}
}
}
struct ParentTaskView: View {
@State var id = 0
var body: some View {
InterruptedTaskView(id: $id)
.id(id) // resets state of child view when changes
}
}
struct InterruptedTaskView: View {
@Binding var id: Int
@StateObject var vm = InterruptedTaskViewModel()
var body: some View {
VStack(spacing: 20) {
Text("Name is \(vm.name) with \(id)")
Button("LOAD") {
vm.load()
id += 1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment