Search code examples
swiftswiftuiswiftui-navigationlinkobservableobjectobservedobject

ObservedObject being loaded multiple times prior to navigation to its view


having a bit of trouble with the following.

I have a List in a VStack as follows:

List{
ForEach(fetchRequest.wrappedValue, id: \.self) { city in
                    
                 NavigationLink(destination: CityView(city: city, moc: self.moc)) {
                            
                            cityRow(city: city)
                 }
                    
         }
}

This list is populated from a coreData fetchrequest. Each NavigationLinks navigates to CityView and passes a city Object with it.

CityView had a observable object 'notificationHandler' defined as follows:

struct CityView: View {

    @ObservedObject var notificationHandler = NotificationHandler()
    @ObservedObject var city: City
    
    var body: some View {

    }
}

NotificationHandler() sets up an instance of NotificationHandler and sets up a few notification observers from within init as follows:

import Foundation
import Combine

class NotificationHandler: ObservableObject {
    
    let nc = NotificationHandler.default
    
    @Published var networkActive: Bool = false
    
    init() {
        nc.addObserver(self, selector: #selector(networkStart), name: Notification.Name("networkingStart"), object: nil)
        nc.addObserver(self, selector: #selector(networkStop), name: Notification.Name("networkingStop"), object: nil)
    }

}

My issues is this - when the app boots onto its first view which contins the list above - I'm getting a number of instance of NotificationHandler starting - one for every row of the list. - This has led me to the belief that the NavigationLinks in the list are preemtivly loading the CityView's they hold. However I believe this is no longer the case and lazy load is the defualt behaviour. To add to that adding an onAppear() within CityView shows the they are not being completly loaded.

Any help would be greatly appretiated, I can't work out how this is happening.

Thanks


Solution

  • The Destination on the NavigationView is NOT lazy, so it initializes the Destination view as soon as it is created. An easy work around can be found here: SwiftUI - ObservableObject created multiple times. Wrap your Destination view within the LazyView.