Created
February 25, 2024 23:48
-
-
Save hmlongco/c14a6c47a0ac77944396e254ab042653 to your computer and use it in GitHub Desktop.
Interrupting a Button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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