Created
December 19, 2020 16:08
-
-
Save ShivamKumarJha/43b8fd90d95ec568328882622333a05e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.shivamkumarjha.myapp.persistence | |
import android.content.Context | |
import androidx.datastore.core.DataStore | |
import androidx.datastore.preferences.core.Preferences | |
import androidx.datastore.preferences.core.edit | |
import androidx.datastore.preferences.core.emptyPreferences | |
import androidx.datastore.preferences.core.preferencesKey | |
import androidx.datastore.preferences.createDataStore | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.catch | |
import kotlinx.coroutines.flow.map | |
import java.io.IOException | |
class DataStorePreference(context: Context) { | |
private val dataStore: DataStore<Preferences> = context.createDataStore(name = "DATA_STORE") | |
private val apiKey = preferencesKey<String>("API_KEY") | |
fun <T> DataStore<Preferences>.getValueFlow( | |
key: Preferences.Key<T>, | |
defaultValue: T | |
): Flow<T> { | |
return this.data | |
.catch { exception -> | |
if (exception is IOException) { | |
emit(emptyPreferences()) | |
} else { | |
throw exception | |
} | |
}.map { preferences -> | |
preferences[key] ?: defaultValue | |
} | |
} | |
suspend fun <T> DataStore<Preferences>.setValue(key: Preferences.Key<T>, value: T) { | |
this.edit { preferences -> | |
preferences[key] = value | |
} | |
} | |
suspend fun getApiKey(): Flow<String> { | |
return dataStore.data.catch { exception -> | |
if (exception is IOException) { | |
emit(emptyPreferences()) | |
} else { | |
throw exception | |
} | |
}.map { preferences -> | |
preferences[apiKey] ?: "" | |
} | |
} | |
suspend fun setApiKey(value: String) { | |
dataStore.edit { preferences -> | |
preferences[apiKey] = value | |
} | |
} | |
companion object { | |
private var INSTANCE: DataStorePreference? = null | |
fun initialize(context: Context) { | |
INSTANCE = DataStorePreference(context) | |
} | |
fun get(): DataStorePreference { | |
return if (INSTANCE != null) { | |
INSTANCE!! | |
} else { | |
throw IllegalStateException("Please initialize DataStorePreference before getting the instance!") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment