Skip to content

Instantly share code, notes, and snippets.

@wesalvaro
Last active June 1, 2022 15:00
Show Gist options
  • Save wesalvaro/5183fa8623bdbe3de4c425161a962ff9 to your computer and use it in GitHub Desktop.
Save wesalvaro/5183fa8623bdbe3de4c425161a962ff9 to your computer and use it in GitHub Desktop.
Creating a `MutableStateFlow` from a Jetpack `ViewModel`'s `SavedStateHandle`.
import androidx.lifecycle.SavedStateHandle
import kotlinx.coroutines.flow.MutableStateFlow
private class SavingFlow<T> private constructor(
private val save: (T) -> Unit,
private val msf: MutableStateFlow<T>
) :
MutableStateFlow<T> by msf {
constructor(
savedStateHandle: SavedStateHandle,
key: String,
initialValue: T
) : this(
{ savedStateHandle.set(key, it) },
MutableStateFlow(savedStateHandle.get(key) ?: initialValue)
)
override var value: T
get() = msf.value
set(value) {
save(value)
msf.value = value
}
}
fun <T> SavedStateHandle.getStateFlow(key: String, initialValue: T): MutableStateFlow<T> {
return SavingFlow(this, key, initialValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment