I have a SharedFlow to emit user data to UI layer ...
# flow
s
I have a SharedFlow to emit user data to UI layer like below, and the user can click a button to call
refresh()
to update
userFlow
(let
emit(userRepository.getUser())
call again.) How do I implement
refresh()
?
Copy code
// ViewModel

val userFlow = flow {
    emit(userRepository.getUser())
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), replay = 1)

fun refresh() {
    // How to reload user?
}
n
Use a MutableSharedFlow and then you can
tryEmit
. 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.
Copy code
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
👍 1