简体   繁体   中英

Can an offline user carry out database transactions specific to their uid in Firebase Realtime Database?

The situation:

User starts the app with no internet connection. I attempt to authenticate them anonymously in my launch activity and perform a database write to the reference '/users/$uid' , in a database with this rule structure:

{
  "rules": {
    "users": {
      "$user_id": {
        ".write": "$user_id === auth.uid",
        ".read": "$user_id === auth.uid"
      }
    }
  }
}

So, if this situation occurs and the user then comes online will the queued database transaction actually be executed - or do I need to manually re-authenticate and retry the database transaction?

I'm not sure if the uid for anonymous authentication will be generated if the user is offline, so I don't think the database reference can be resolved.

Reference links:

https://firebase.google.com/docs/auth/android/anonymous-auth https://firebase.google.com/docs/database/android/offline-capabilities

I would save the data in sharedpreferences or local DB (depends on the type of data you want to save).

After that either start background service and try to connect to your realtime database every 10mins or you want for the user next time they open the app and check if theres any authentication need to be checked.

For the background service i would recommend AlarmManger.

So, after testing this, I've found that:

  • The uid cannot be relied upon between restarts if the user never had connectivity in the first place
  • Database transactions which are performed locally - because you have setPersistence(true) - will be queued and synced with remote, regardless of whether the user has connectivity or not, but not if the DatabaseReference used contains a reference to the current user's uid, because this cannot be relied upon between restarts (such as in the scenario described in the question).

To get around this, I'm using local storage by means of SharedPreferences for the most basic data and waiting for connection before instantiating a DatabaseReference which references the user's uid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM