How to call a func from another model inside snapshot listener?

Hi CodeCrew,

Any help is much appreciated…

To make it simple… I have two models:

  • UserModel() which handles users and
  • CoreDataModel() which handles saving data into CoreData…

Upon app launch, I call a func enableUserListener() that listens from DB update from User Colletion in Firestore… This is all working… What I need help is how do I call any func in CoreDataModel so I can update the User in CoreData when there is new update on the User DB…

I can do something like below and call func saveUserToCoreData() under addSnapshotListener completion. However this doesn’t work because the line "let coreDataModel = CoreDataModel()" creates a new instance of the CoreModel…

Can you help how to solve this issue?

class UserModel: ObservableObject {
    func enableUserListener() {
        ....
        userRef.addSnapshotListener{ snapShot, error in
            ....
            ....
            saveUserUpdateToCoreData()
        }
    }

    func saveUserToCoreData(user: User) {
        let coreDataModel = CoreDataModel()
        
        coreDataModel.addUser(user: user)
    }
}

class CoreDataModel: ObservableObject {
    func addUser(user: user) {
        ....
    }
}

Thanks…

Cheers,

@ChaseCooks

Hi Chauncey,

Does the snapshot listener update a Published property, presumably an array, in your UserModel?

If so then in your View that deals with users, set up an .onChange(of.... that monitors that Published property and when a change occurs make an update to your CoreDataModel.