Pablo
12/15/2024, 6:55 PMval uiState: StateFlow<BusStopsDBScreenUiState> = busDataRepository.getBusStops()
.map<List<BusStop>, BusStopsDBScreenUiState> { busStops ->
BusStopsDBScreenUiState.Success(busStops, Res.string.bus_stops_db_filled)
}
.catch { throwable ->
emit(BusStopsDBScreenUiState.Error(throwable))
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), BusStopsDBScreenUiState.Loading)
I added a message dialog that displays the number of items obtained from the database, and it is displayed when the dialogText
message is different from null. The dialogText
is on my Success uistate as follows:
sealed interface BusStopsDBScreenUiState {
object Loading : BusStopsDBScreenUiState
data class Error(val throwable: Throwable) : BusStopsDBScreenUiState
data class Success(
val data: List<BusStop>,
val dialogText: StringResource?
) : BusStopsDBScreenUiState
}
The problem now is that I need to set null that dialogText
variable, to hide the dialog, so I need a method for that on the viewmodel:
fun closeDialog() {
//TODO set dialogText to null
}
but... I don't understand how can I change the dialogText to null without breaking my stateflow val. Some people here tell me that I need to use mutablestateflow, but I don't know how to change my code to achieve it. Please can someone explain me?KamilH
12/15/2024, 7:03 PMprivate val dialogText: MutableStateFlow<StringResource>? = MutableStateFlow(null)
and then
val uiState: StateFlow<BusStopsDBScreenUiState> = combine(dialogText,
busDataRepository.getBusStops()) {
(...)
}
and then
fun closeDialog() {
dialogText.update { null }
}
Pablo
12/15/2024, 7:07 PMPablo
12/15/2024, 7:07 PMPablo
12/15/2024, 7:08 PMKamilH
12/15/2024, 7:19 PMprivate val dialogText: MutableStateFlow<StringResource>? = MutableStateFlow(null)
you could have:
private val uiEvent: Channel<UiEvent>
and then:
fun closeDialog() {
uiEvent.tryEmit(DialogCloseRequested)
}
or something like this.
I think Ballast’s documentation has a good explanation of the different presentation layer patterns:
https://copper-leaf.github.io/ballast/wiki/usage/mental-model/#mviChrimaeon
12/15/2024, 8:13 PMPablo
12/16/2024, 11:41 AMPablo
12/16/2024, 11:42 AMval uiState: StateFlow<BusStopsDBScreenUiState> = busDataRepository.getBusStops()
.map<List<BusStop>, BusStopsDBScreenUiState> { busStops ->
BusStopsDBScreenUiState.Success(busStops, Res.string.bus_stops_db_filled)
}
.catch { throwable ->
emit(BusStopsDBScreenUiState.Error(throwable))
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), BusStopsDBScreenUiState.Loading)
but I can't change val uiState: StateFlow
to val uiState: MutableStateFlow
and initialize it in the same way, it doesn't compilePablo
12/16/2024, 11:43 AMType mismatch. Required:MutableStateFlow<BusStopsDBScreenUiState> Found:StateFlow<BusStopsDBScreenUiState>
Pablo
12/16/2024, 11:43 AM