Syncing between Firestore and Realm

Hi. I want to implement syncing feature that synchronizes data between Realm in local device and remote firestore. While when having records added to realm, I can also push it to firestore, but I dont now how to do so in opposite direction. I want to update local realm when new records added to firestore. How can I implement this. Thanks you all in advance.

That should be pretty straight forward:

In Firestore, you would add an observer to a collection (for example) and when something changes in that collection your app is notified within the observer closure.

You can process the changes in a broad way - like an entire document or you can be more granular with added, change and removed events.

Once you have the data that was change within that closure, update your local realm object. Here’s a Firestore Swift function that will receive changes to a Users collection, so you can then update your local Realm objects. This code prints the users name and I commented where the realm code would go.

func observeUserCollectionChanges() {
    let usersCollectionRef = self.db.collection("users") //self.db points to my Firestore
    usersCollectionRef.addSnapshotListener { querySnapshot, error in
        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")

        //process fine-grained changes
        snapshot.documentChanges.forEach { diff in
            let userName = diff.document.get("name") as? String ?? "No Name"
            if (diff.type == .added) {
                print("Added user: \(userName)")
                //add the user to Realm
            if (diff.type == .modified) {
                print("Modified user: \(userName)")
                //modify and existing user
            if (diff.type == .removed) {
                print("Removed user: \(userName)")
                //delete the user. So there.

My question is - and I have been using Firebase since the beginning - why not just use Realm Sync’ing?

You’ll have a lot of the same capabilities; Firestore is an Online First Model wheras Realm is Offline First, if you want to sync the data and store it locally anyway, you may be able to just use Realm and simplify the codebase and app.


Thank you, @Jay . Very straight and on point reply. About the reason I use both Realm and Firestore: My system has apps and devices that connect to each others and firestore is used as central database. I also have to use Realm as my app intended as offline first.

I would encourage checking out Realm Sync capabilities as they may provide similar services to Firebase Firestore (for this use case); multiple users apps and devices with a centralized database across apps.

1 Like