SwiftUI re-renders inactive View after updating @Published property asynchronously

Viewed 169

We are using SwiftUI with a NavigationView.

We have one view (ParentView) that updates its data asynchronously through its view model (ParentViewModel) and then re-renders its body according to the new data. When the completion block is called after we have entered the second view (ChildView) through the NavigationLink, problems occur, e.g. the app automatically navigating back to the first view without any user interaction, or missing completion block calls in the second view.

struct ParentView: View {

    @ObservedObject private var viewModel = ProjectListViewModel()

    var body: some View {
        ForEach(viewModel.items) { item in
            NavigationLink(destination: ChildView(item: item)) {
                Text(item.label)
            }
        }.onAppear(perform: viewModel.loadData))
    }
}

class ParentViewModel: ObservableObject {

    @Published var items: [Item] = []

    func loadData() {
        loadDataAsynchronously { [weak self] newItems in
            // Problems occur if this completion block is called after we have entered ChildView
            self?.items = newItems
        }
    }
}

class Item: Identifiable { ... }

This error occurs on the simulator as well as on a physical device.

0 Answers
Related