Search code examples
swiftrealmmongodb-atlasrealm-mobile-platform

Destroy or Reset singleton Realm Repo after logout?


I use my Realm repo as a singleton class all over my views.

I use the repo like:

var repo = SingletonRepo.shared

The singleton class:

class SingletonRepo{
    static let shared = RealmRepo()
    
    private init() { }
}

Everything works fine until a logout and re-login happens. The realm syncs get inactive.

This happens, I think, because the singleton does not get reseted/destroyed on the re-login.

What is the best way to solve this problem? Destroy or Reset the repo? Where should I do that? In the login method or at the logout?

Also how I can do this on the same singleton class? Create a method reset/delete repo?

I ve solved this by:

Adding a reset method to the singleton:

class SingletonRepo{
    static var shared = RealmRepo()
    
    private init() { }
    
    static func reset() {
            shared = RealmRepo()
        }
    }

And I call the reset method on the logout:

func doLogout(){

        repo.doLogout(token: myFCMToken){error in
            SingletonRepo.reset()
            UserDefaults.standard.set(false, forKey: "isLogin")
            isLoginShown = true
        }
        
    }

Also, I still only use the repo like this:

var repo = SingletonRepo.shared

I tested and it works, but is this a good solution?


Solution

  • One possible solution can be you can create realm repo based on user logged in, I mean totally user centric repo.

    Like:

       class LoginUser {
          var realmRepo:RealmRepo = RealmRepo()
       }
    
       class RealmRepo {
       }
    

    After user login create a user instance Like: let user = LoginUser()

    Now access RealmRepo Like this way: let repo = user.realmRepo

    Now use this repo for all your purpose

    When user log out simply make the user nil, like: user = nil

    by setting nil to logged in user will also discard/destroy your repo too

    So this way for every new user, new instance of realmRepo will be created and after log out when you set user=nil repo will be discarded.

    And I hope this way your sync issue will be fixed too