Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mutableStateOf for SharedPreferences
import android.content.SharedPreferences
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.edit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun SharedPreferences.mutableStateOf(
key: String,
defaultValue: String? = null,
): ReadWriteProperty<Any?, String?> = object : ReadWriteProperty<Any?, String?> {
private val cached: MutableState<String?> = mutableStateOf(defaultValue)
val onSharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey ->
if (key == changedKey) {
cached.value = getString(key, defaultValue)
}
}
init {
// don't pass onSharedPreferenceChangeListener as an anonymous lambda, it will be GC'd!
registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): String? =
cached.value ?: getString(key, defaultValue).also { cached.value = it }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) {
cached.value = value
edit(commit = false) {
putString(key, value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment