I have faced an issue in an Android app where Kotlin's flow will no longer be able to execute the same code specified in its body while it has been executed before and failed (so an exception has been emitted).
Since Kotlin's flow works like a stream, can I reuse the same flow to emit new values after failure?
For example: A flow has been executed to do a network request and failed for some reason, it would be a good use case if the user clicks "Try again" so I can use the same flow and retry the same execution.
Can any of the "retry" operators of Kotlin's flow be useful in my use case?
Also, I am aware that If I make a new flow object will resolve my issue, but my question is, can I reuse the flow object in such cases. And is my reasoning for reusing the flow even valid and makes sense?
Please and thank you.
CodePudding user response:
In general, it's safe to reuse the same flow and collect it again, even after failure. It should simply re-execute the body of the flow.
If this was not the case for you in some app, it was probably an issue with the body of that particular flow.
You can try this yourself:
val flow = flow {
emit(1)
emit(2)
error("BOOM")
}
println(flow.first())
println(runCatching { flow.toList() })
println(flow.take(2).toList())
This prints:
1
Failure(java.lang.IllegalStateException: BOOM)
[1, 2]
Can any of the "retry" operators of Kotlin's flow be useful in my use case?
retry does exactly that: it collects again if the upstream throws an exception that matches the predicate.
That doesn't mean you should use this operator for your specific use case, because I guess the fact that you want user confirmation might probably require a bit more code, probably manually recollecting.
