Skip to content

Instantly share code, notes, and snippets.

@iNuman
Created April 29, 2021 11:58
Show Gist options
  • Select an option

  • Save iNuman/e5c6e4acb3f59c6b579975c1b8015330 to your computer and use it in GitHub Desktop.

Select an option

Save iNuman/e5c6e4acb3f59c6b579975c1b8015330 to your computer and use it in GitHub Desktop.
Object class for managing Datastore Utils same as SharedPreferences
package com.sourcefixxer.gallery.datastore_utils
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
const val APP_ID_KEY = "application_id"
const val BANNER_AD_ID_KEY = "banner_id"
const val INTERSTITIAL_AD_ID_KEY = "inters_id"
const val NATIVE_AD_ID_KEY = "native_id"
const val ALLOW_ADS_ON_BACKPRESS_KEY = "backpress_ads"
var BANNER_AD_VALUE = "value"
var INTERS_AD_VALUE = "i_value"
var NATIVE_AD_VALUE = "n_value"
var APP_ID_VALUE = "a_value"
object DataStoreUtil {
suspend fun Context.write(key: String, value: String) {
dataStore.edit { settings ->
settings[stringPreferencesKey(key)] = value
}
}
suspend fun Context.read(key: String, defaultValue: String): String {
return dataStore.data.map { settings ->
settings[stringPreferencesKey(key)] ?: defaultValue
}.first().toString()
}
suspend fun Context.write(key: String, value: Int) {
dataStore.edit { settings ->
settings[intPreferencesKey(key)] = value
}
}
suspend fun Context.read(key: String, defaultValue: Int): Int {
return dataStore.data.map { settings ->
settings[intPreferencesKey(key)] ?: defaultValue
}.first().toInt()
}
suspend fun Context.write(key: String, value: Double) {
dataStore.edit { settings ->
settings[doublePreferencesKey(key)] = value
}
}
suspend fun Context.read(key: String, defaultValue: Double): Double {
return dataStore.data.map { settings ->
settings[doublePreferencesKey(key)] ?: defaultValue
}.first().toDouble()
}
suspend fun Context.write(key: String, value: Boolean) {
dataStore.edit { settings ->
settings[booleanPreferencesKey(key)] = value
}
}
suspend fun Context.read(key: String, defaultValue: Boolean): Boolean {
return dataStore.data.map { settings ->
settings[booleanPreferencesKey(key)] ?: defaultValue
}.first()
}
suspend fun Context.clear() {
dataStore.edit { it.clear() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment