How can I set an initial state when mapping a flow...
# coroutines
o
How can I set an initial state when mapping a flow. Here's an example that explains what I mean:
Copy code
val dataUiState: StateFlow<UiState<Data>> = queryFlow
        .debounce(300)
        .mapLatest {
            // How to set state to UiState.Loading while request is still running

            // Get new data based on filter
            val data = requestData(it)
           UiState.Success(data)
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), UiState.Loading)
I would like to reset the state to
UiState.Loading
while the data request is still fetching.
z
Instead of
mapLatest
you could use
flatMapLatest
and make a flow that starts with loading, or probably simpler to just use
transformLatest
and emit loading before emitting the load result.
s
Or update queryFlow's state outside of the chain of transformations forming dataUiState. dataUiState.update { .... requestData(it) ... } in another method that would initiate the requestData call
o
Thanks,
transformLatest
was exactly what I needed