Skip to content

Instantly share code, notes, and snippets.

@ishanvohra2
Created February 14, 2024 05:40
Show Gist options
  • Save ishanvohra2/d79de57631d293a6e546a3678e9dd58b to your computer and use it in GitHub Desktop.
Save ishanvohra2/d79de57631d293a6e546a3678e9dd58b to your computer and use it in GitHub Desktop.
class DatastoreManager(
private val context: Context
): DataStorePreferenceAPI {
companion object{
fun getInstance(context: Context) = DatastoreManager(context)
//Create an instance of the datastore
private val Context.dataStore by preferencesDataStore(
name = "my_datastore"
)
}
//Return the value stored in the datastore via a Flow (stream of data)
override suspend fun <T> getPreference(key: Preferences.Key<T>):
Flow<T?> = context.dataStore.data.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
preferences[key]
}
//Write a preference using a key and its value
override suspend fun <T> putPreference(key: Preferences.Key<T>, value: T) {
context.dataStore.edit { preferences ->
preferences[key] = value
}
}
//Delete a specific preference
override suspend fun <T> removePreference(key: Preferences.Key<T>) {
context.dataStore.edit {
it.remove(key)
}
}
//Clearing all preferences
override suspend fun clearAllPreference() {
context.dataStore.edit { preferences ->
preferences.clear()
}
}
}
//Generic API to write/read onto the DataStore Preferences easily
interface DataStorePreferenceAPI {
suspend fun<T> getPreference(key: Preferences.Key<T>): Flow<T?>
suspend fun<T> putPreference(key: Preferences.Key<T>, value: T)
suspend fun<T> removePreference(key: Preferences.Key<T>)
suspend fun clearAllPreference()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment