'Swift Singleton Pattern in Conjunction With Cloud Firestore
I have been looking into cloud firestore as my backend infrastructure. Ive been using realtime database but feel the switch is vital. I have looked at the firebase documentation and I am considering using a singleton pattern to manage the data transactions, however I am unsure the ramifications as there is little mention that I could find online. Is there any information on best practice design patterns in conjunction of cloud firestore.
Solution 1:[1]
It's quite a late answer but that's how I am using Firestore with a singleton pattern... hoping it helps others...
struct RemoteConfigManager {
    
    static var sharedDB = RemoteConfigManager()
    
    let db = Firestore.firestore() //FIRFirestore
    
    var listener : ListenerRegistration?
    
    private init(){}
    
    mutating func getData(){
        listener = db.collection("myCollection").addSnapshotListener { (snapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in snapshot!.documents {
                    let myValue = document.get("myKey") as! Bool
                   //other stuff 
                }
            }
        }
        
        
    }
     func detachListener(){
        listener?.remove()
      }
    }
The following code shows how to use this struct...
    //instance for FireStore
    var db : RemoteConfigManager?  
    //use this method after configring the GoogleService.plist file
    func firebaseRemoteConfig() {
        db = RemoteConfigManager.sharedDB
        db?.getData()
    }
call the following line when detachListener
 db?.detachListener()
I am detaching on applicationWillTerminate method of AppDelegate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
