bibin-jaimon / InterviewKit-iOS

5 stars 0 forks source link

How can I ensure the .task modifier is called only once in SwiftUI? #28

Open bibin-jaimon opened 2 months ago

bibin-jaimon commented 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.