Last active
June 1, 2022 15:00
-
-
Save wesalvaro/5183fa8623bdbe3de4c425161a962ff9 to your computer and use it in GitHub Desktop.
Creating a `MutableStateFlow` from a Jetpack `ViewModel`'s `SavedStateHandle`.
This file contains 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
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