Home > Enterprise >  How to check if something was saved or not to a DataStore flow in Android Studio?
How to check if something was saved or not to a DataStore flow in Android Studio?

Time:09-20

I am building an app in which I need to save a piece of data (a boolean) to DataStore. But I only need to save it once (when the app runs for the very first time). How can I start the app for the first time, check if that boolean was or wasn't saved, and if it wasn't, save the data and prevent it from saving again next time the app is opened?

CodePudding user response:

In your DataStore you can have something like this:

val yourBooleanKey = booleanPreferencesKey("yourBooleanKey")

suspend fun getYourBoolean(): Boolean? {
    dataStore.data.map {
       it[yourBooleanKey]
    }.firstOrNull()
}

suspend fun setYourBoolean(value: Boolean) {
    dataStore.edit {
       it[yourBooleanKey] = value
    }
}

And then just check whether your boolean value is null or not:

if (dataStore.getYourBoolean() == null) {
    dataStore.setYourBoolean(yourBooleanValue)
}
  • Related