In my Android ViewModel I have code like this:
try {
myRepository
.getAllData()
.catch {
Timber.e("catch exception case 1")
Timber.e(it)
}
.collect { data ->
// use data to set UI state
uiState = uiState.copy(data = data)
}
} catch(e: Exception) {
Timber.e("catch exception case 2")
Timber.e(e)
// how to keep the flow alive or restart it?
}
During testing I reached
catch exception case 2. In this case I want to display an error to the user, but keep theFlowalive (e.g. if users presses a retry button which could then send successful data over theFlow). However in my understanding theFlowis automatically cancelled due to the exception? How to restart theFlowor prevent it from being cancelled at all?In which case would one reach
catch exception case 1?
You should use
retryWheninstead ofcatch, it's the most powerful operator for working with exceptions inFlow.It allows you to:
ThrowableFlow.Conceptually you could do something like this:
Unless
uiState = uiState.copy(data = data)can throw an exception, which I assume it won't. This code will never fail.To make it fail, you should either return
falsetoretryWhenor re throw a different exception from withinretryWhen.