Log out best practises

What is the best practise when logging out a user in a realm offline first application?

In the docs it says:
"You can log out any user, regardless of the authentication provider used to log in, using the user.logOut() or user.logOutAsync() methods. Both methods:

  • delete locally stored user credentials from the device
  • immediately halt any synchronization to and from the user’s realms
  • mark the user’s realms for deletion the next time the app restarts

Because logging out halts synchronization, you should only log out after all local Realm updates have uploaded to the server."

As I understand this, if a user logs out while being offline, all recently changed data by this user is deleted and no longer present on the next login. How can I prevent this from happening.

I could check whether a user has internet connection and only allow users to logout if they have. But what if the connection is poor, but present and not all changes have been uploaded yet? Can I check somehow if the data is up to date with the server, before logging the user out?

Hi Annika,

Welcome to the forum.

As I understand this, if a user logs out while being offline, all recently changed data by this user is deleted and no longer present on the next login. How can I prevent this from happening.

Your understanding is correct here, and demonstrates a tricky use case that we haven’t quite ironed out yet. Right now, I can recommend the following:

  1. When a user decides to log out, call SyncSession.uploadAllLocalChanges() first. This method will block until all of the current user’s local changes have synced to the MongoDB Realm backend.
  2. After SyncSession.uploadAllLocalChanges() returns, call logout() or logoutAsync().

This will guarantee that no local changes are lost on user logout. However, you should be aware that because SyncSession.uploadAllLocalChanges() blocks until all local changes complete, it could take a while (or forever!) if a user is truly offline or has a lot of changes to upload on a weak connection. So you’ll have to decide based upon your particular use case if it makes sense to cancel a user’s logout until they have a chance to synchronize local changes, or always fall back to a successful logout at the potential cost of losing local changes.

Hopefully this helps you solve your problem. Thanks for asking such a thoughtful question!

PS: We recognize that this solution is a bit boilerplate-y, so we just opened a new issue on the Android SDK (https://github.com/realm/realm-java/issues/7289) to make this process a little bit easier. Thanks for giving us the idea.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.