Activity code which is collecting the flow as state and updating the UI based on the state emitted by the Flow.
setContent {
val viewModel: MainViewModel = viewModel()
val state: State<UiState> = viewModel.flow.collectAsStateWithLifecycle(
initialValue = UiState.Loading,
lifecycle,
minActiveState = Lifecycle.State.STARTED
)
MainScreen(uiState = state.value)
}
ViewModel code which is exposing the StateFlow
val flow: Flow<UiState> = repository.flow
.map {
if (it.datetime == "") {
emit(UiState.Error("Failure"))
} else {
UiState.Success(it.datetime)
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = UiState.Loading
)
Cold flow exposed by the repository:
val flow = flow {
while (true) {
delay(5000)
emit(getCurrentTime())
}
}.catch {
// Emit Empty Object which will be treated as an error
emit(CurrentTime(""))
}
If there is an exception in the upstream cold flow which is exposed by the Repository, there will no more emissions from the upstream flow as it gets completed. We can emit an UiState.Error in such case to the UI (shown above).
Is there a way we can retrigger the upstream flow again once the UI is in error state.