Skip to content

Instantly share code, notes, and snippets.

@ravisorathiya
Created April 4, 2024 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravisorathiya/5acc5a375510b12fb04fd247c91e6868 to your computer and use it in GitHub Desktop.
Save ravisorathiya/5acc5a375510b12fb04fd247c91e6868 to your computer and use it in GitHub Desktop.
class AppDataStoreManager private constructor(val context: Application) : AppDataStore {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
companion object {
@Volatile
private var INSTANCE: AppDataStoreManager? = null
fun getInstance(context: Application): AppDataStoreManager {
return INSTANCE ?: synchronized(this) {
val instance = INSTANCE
if (instance == null) {
INSTANCE = AppDataStoreManager(context)
}
INSTANCE!!
}
}
}
override suspend fun <T> setValue(key: Preferences.Key<T>, value: T) {
context.applicationContext.dataStore.edit { it[key] = value }
}
override suspend fun <T> readValue(key: Preferences.Key<T>): T? {
return context.applicationContext.dataStore.data.first()[key]
}
override suspend fun <T> deletePrefKey(key: Preferences.Key<T>) {
val dataStore = context.applicationContext.dataStore
dataStore.edit { it.remove(key) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment