UI freezes when using FirestoreDecoder to decode Firestore documents

Viewed 248

I'm fetching data from Firestore, mapping the documents and decoding each of them using FirestoreDecoder. However, decoding the documents momentarily freezes the UI. Running the code on the background thread makes no difference. How can I prevent the UI from freezing during the decoding?

    let collection = Firestore.firestore().collection("roll_groups")
    
    collection.addSnapshotListener { (snapshot, error) in
        if let error = error {
            print("Error fetching roll groups: \(error.localizedDescription)")
        } else if let snapshot = snapshot {
            DispatchQueue.global(qos: .background).async {
                let rollGroups = snapshot.documents.map { doc -> RollGroup? in
                    do {
                        let rollGroup = try FirestoreDecoder().decode(RollGroup.self, from: doc.data())
                        return rollGroup
                    } catch {
                        print("Error decoding roll groups: \(error)")
                        return nil
                    }
                }
                
                DispatchQueue.main.async {
                    completion(rollGroups)
                }
            }
        }
    }
1 Answers

Possible Solution

Looking at this code it all seems fine, I just want to confirm that the completion for your method is definitely a @escaping: completion() otherwise it could cause this issue

also, it might be worth wrapping the actual DB call (collection.addSnapshotListener) in

DispatchQueue.global(qos: .background).async

Just to see if that Makes a difference, in theory it shouldn't but nonetheless it's worth a shot

Related