androidkotlindatastore

How to check if there is data saved in DataStore in Android?


This is my UserManager.kt Class which has a function to save and map data but how do create a function which tells me that datastore has user or not?

    class UserManager(context: Context) {

    private val dataStore = context.createDataStore(name = "user_prefs")

    companion object {
        val USER_NAME_KEY = preferencesKey<String>("USER_NAME")
        val USER_NUMBER_KEY = preferencesKey<Int>("USER_NUMBER")
    }

    suspend fun storeUser(number: Int, name: String) {
        dataStore.edit {
            it[USER_NUMBER_KEY] = number
            it[USER_NAME_KEY] = name

        }
    }

    val userNumberFlow: Flow<Int> = dataStore.data.map {
        it[USER_NUMBER_KEY] ?: 0
    }

    val userNameFlow: Flow<String> = dataStore.data.map {
        it[USER_NAME_KEY] ?: ""
    }
}

Solution

  • You can treat with the DataStore as a map, and check if it contains your key or not.

    You need to pass your key as a paramter to the below method, and it will return true or false based on the availibility of the key.

    fun isKeyStored(key: Preferences.Key<String>): Flow<Boolean>  = 
        context.dataStore.data.map {
                preference -> preference.contains(key)
        }