Simon Lin
12/03/2021, 2:36 AMrefresh() to update userFlow (let emit(userRepository.getUser()) call again.)
How do I implement refresh() ?
// ViewModel
val userFlow = flow {
emit(userRepository.getUser())
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), replay = 1)
fun refresh() {
// How to reload user?
}Nick Allen
12/03/2021, 3:41 AMtryEmit. Then you can build your userFlow off of that. And I always recommend using StateFlow instead of having the UI code wait for an initial value.
val refreshes = MutableSharedFlow<Unit>(
extraBufferCapacity = 1, //hold the "event"
onBufferOverflow = BufferOverflow.DROP_LATEST //no need to refresh if you already will
)
fun refresh() {
refreshes.tryEmit(Unit)
}
val userFlow = refreshes //All you refresh events
.onStart { emit(Unit) //An initial event to start
.mapLatest { userRepository.getUser() } //mapLatest will cancel call if new refresh comes in
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null) //null can mean loading