I want the view to be updated every time @State list gets updated. But when I use Button to trigger a consecutive update, the list gets updated only after all the consecutive updates are finished.
This code updates the list 10 seconds after the button is pressed. What should I do to make this code update every second?
@State var i_list: [Int] = []
var body: some View {
VStack {
Button(action: {
for i in 0..<10 {
i_list.append(i)
do {
sleep(1)
}
}
}) {
Text(button_text)
}
List (i_list, id: \.self){ i in
Text(String(i))
}
}
}
Solved:
I solved this problem by updating the list in a different thread.
let globalQueue = DispatchQueue.global()
globalQueue.async {
for i in 0..<10 {
DispatchQueue.main.async {
i_list.append(i)
}
do {
sleep(1)
}
}
}