Skip to content

Instantly share code, notes, and snippets.

@Aidanvii7
Last active March 24, 2022 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aidanvii7/f2e72ce8dc95ef2ba798eafd700cc47d to your computer and use it in GitHub Desktop.
Save Aidanvii7/f2e72ce8dc95ef2ba798eafd700cc47d to your computer and use it in GitHub Desktop.
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