Migrating to Combine causes Snapshotlistener to fail

Viewed 364

I am migrating the codebase to Combine and the snapshotlistener isn't working i.e. when the document is updated in the back-end, it doesn't get reflected in the app.

This is where I call the service from the Controller:

@objc func loadPlans() {
    guard let userEmail = userEmail else { return }
    getPlansToken = PlanService.sharedInstance.queryPlans(userEmail: userEmail)
        .receive(on: DispatchQueue.main)
        .sink { (completion) in
        switch completion {
        case .failure(let error):
            self.showAlert(alertTitle: "Error", message: error.localizedDescription)
        case .finished:
            print("Publisher stopped observing")
        }
    } receiveValue: { (mealplans) in
        self.mealplanArray.removeAll()
        self.mealplanArray = mealplans.map({return PlanViewModel(mealplan: $0)})
        self.planTableView.reloadData()
        self.refreshControl.endRefreshing()
    }
}

And this is the service:

var listener : ListenerRegistration!
let db = Firestore.firestore()
static let sharedInstance = PlanService()

func queryPlans(userEmail: String) -> Future<[Mealplan], Error> {
    var mealplans = [Mealplan]()
    return Future { promise in
        self.listener = self.db.collection("Meal_Plans")
            .whereField("userId", isEqualTo: userEmail)
            .order(by: "timeOfCreation", descending: true)
            .addSnapshotListener({ (querySnapshot, error) in
                guard let documents = querySnapshot?.documents else {
                    print("No mealplans")
                    return
                }
                mealplans = documents.compactMap { queryDocumentSnapshot -> Mealplan? in
                    return try? queryDocumentSnapshot.data(as: Mealplan.self)
                }
                promise(.success(self.updateTimeZone(source: mealplans)))
                if let error = error {
                    promise(.failure(error))
                }
        })
    }
}
0 Answers
Related