Home > Mobile >  tableview.reloaddata() still works outside of Dispatchqueue.main.sync when we retrieve data from Fir
tableview.reloaddata() still works outside of Dispatchqueue.main.sync when we retrieve data from Fir

Time:09-22

The rule is that "if you update the user-interface inside a closure that works in another thread, then you should call in DispatchQueue.main.async method. However, after I retrieved the data from the Firestore, tableview.reloadData() still works without the existence of DispatchQueue.main.async method and it works in MainThread inside the closure. How would be it possible? Is something changed? Xcode version 12.4; Swift version 5

   func loadMessages(){
    messages = []
    
    db.collection(K.FStore.collectionName).getDocuments { (querySnapShot, error) in
        if let err = error {
            print("There was an issue retrieving data from Firestore. \(err)")
        }else{
            if let snapShotDocuments = querySnapShot?.documents{
                for doc in snapShotDocuments{
                    let data = doc.data()
                    if let messageSender = data[K.FStore.senderField] as? String,let messagebody = data[K.FStore.bodyField] as? String{
                        let newMessage = Message(sender: messageSender, body: messagebody)
                        self.messages.append(newMessage)
                    }
                }
            }
            if Thread.isMainThread{
                self.tableView.reloadData()
            }
        }
    }
}

CodePudding user response:

The Firestore SDK (and most Firebase SDKs) invoke your callback on the main thread, precisely so that you can easily update the UI. They transition to the main thread, so that you don't have to.

Also see my answer here:

  • Related