satyan
12/08/2020, 7:55 PMDaniel
12/09/2020, 10:18 PMallan.conda
12/10/2020, 9:55 AMsatyan
12/10/2020, 3:41 PMHow does StateFlow behave when the screen is recrated (rotation)?
Also if the answer is: The value is observed again, how would it be possible to make a SingleLiveDataEvent with StateFlow? With other words: A value wich is really only observed one time and then consumedI had a part about SingleLiveEvent initially, but it was going to be too long. You can use a SharedFlow instead of a StateFlow On collect, a SharedFlow will emits its replay cache then emit the next values, so you can use a SharedFlow with a replay cache of 0
class MyViewModel {
private val _toast = MutableSharedFlow<String>() // by default replay cache is 0
val toast: SharedFlow<String> = _toast
fun foo() {
viewModelScope.launch {
// suspend until collected
_toast.emit("Hello")
}
}
}
Oh, just in time, I’m literally doing this right now.
Seems there’s no info about savedStateHandle? That’s kinda the blocker for me right now.What do you mean ? I used savedStateHandle to save data but it’s only going to be use initially to restore the state.
class MyViewModel (savedStateHandle: SavedStateHandle) {
val _state = MutableStateFlow(restoreState())
val state: StateFlow<State> = _state
private fun restoreState(): State {
return savedStateHandle.get(KEY) ?: INITIAL_STATE
}
}
⚠️ If your state is big, you should only save part of it and restore the full state. For example, if your state is a paginated list, instead of saving the whole list, you could save the current page/token and then restore the items using itallan.conda
12/10/2020, 4:10 PMsatyan
12/10/2020, 4:21 PMfun foo() {
viewmodelScope.launch {
val user = userRepository.getUser(id)
_state.value = mapper.mapState(user) savedStateHandle[KEY] = user
}
}
allan.conda
12/10/2020, 4:56 PMsatyan
12/10/2020, 5:44 PMallan.conda
12/10/2020, 5:56 PMDaniel
12/10/2020, 8:44 PM