Reputation: 555
While having a NavigationLink set-up like so in Xcode Version 11.4.1 (11E503a):
NavigationView {
vm.isShowingBarCharts ? Text("Charts") : Text("List")
}.navigationBarItems(
NavigationLink(destination: LEditView(vm: LEditViewModel())) {
LIcons.addEntry
.resizable()
.frame(width: 20, height: 20)
}
)
vm.isShowingBarCharts being a Published of type Bool, the view gets re-drawn (as expected) if vm.isShowingBarCharts gets flipped. What I don't understand is, why multiple LEditViewModel() instances are getting instantiated?
How that can be avoided?
Upvotes: 1
Views: 1752
Reputation: 3560
I was using Timer Publisher which was causing each time redraw view and each second view was being navigated. So, I need to cancel Timer Publisher when the view is about to Navigate to the next view.
viewModel.cancellable?.cancel()
Helps me to solve the issue, where viewModel.cancellable
is Combine
's Cancellable
.
Upvotes: -1
Reputation: 555
With Xcode 12.1(12A7403) iOS 14.0 + this can be fixed by using the @StateObject property wrapper. If not using @StateObject, the VM will be instantiated every time the parent is re-drawn.
Upvotes: 2