-
-
Save ishanvohra2/d79de57631d293a6e546a3678e9dd58b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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