I have a settings screen where I am setting some values. When I set those values it gets saved in shared preferences and these values are needed in my request to the network
Android recently released DataStore which is:
Jetpack DataStore is a data storage solution that allows you to store key-value pairs or typed objects with protocol buffers. DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally.
If you're currently using SharedPreferences to store data, consider migrating to DataStore instead.
So here is the breakdown:
In the build.gradle of the project:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
dependencies {
...
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha04"
}
The database class would look like:
class SettingsSharedPreference private constructor(context: Context) {
private val dataStore = context.createDataStore(name = "settings")
companion object {
val SCREEN_ORIENTATION = preferencesKey("screen_orientation")
@Volatile
private var instance: SettingsSharedPreference? = null
private val lock = Any()
operator fun invoke(context: Context) = instance ?: synchronized(lock) {
instance ?: SettingsSharedPreference(context).also { instance = it }
}
}
val screenOrientationFlow: Flow = dataStore.data
.map { preferences ->
preferences[SCREEN_ORIENTATION] ?: "landscape"
}
//TODO: You should use enum for screenOrientation, this is just an example
suspend fun setScreenOrientation(screenOrientation: String) {
dataStore.edit { preferences ->
preferences[SCREEN_ORIENTATION] = screenOrientation
}
}
}
In the Activity:
val settingsSharedPreference by lazy {
SettingsSharedPreference.invoke(this)
}
...
settingsSharedPreference.setScreenOrientation("portrait")
...
settingsSharedPreference.screenOrientationFlow.asLiveData().observe(this) { screenOrientation ->
...
}