Open bibin-jaimon opened 2 months ago
If we want to execute a task only once, then we can do the following approach.
final class ViewModel: ObservableObject { @Published var items: [Int] = [] func updateItem() { DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [weak self] in self?.items = [1,2,3,4] } } }
struct MyComponent: View { @StateObject var vm = ViewModel() var body: some View { if vm.items.isEmpty { ProgressView() .task { [weak vm] in vm?.updateItem() } } else { List(vm.items, id: \.self) { item in Text("\(item)") } } } }
Once we render the list then the task will be removed and won't execute again.
If we want to execute a task only once, then we can do the following approach.
Once we render the list then the task will be removed and won't execute again.