Is the a way to resume a flow on error? ```fun mai...
# coroutines
b
Is the a way to resume a flow on error?
Copy code
fun main() = runBlocking<Unit> {
    emit()
        .onEach {
            if (it == 5) error("oof! some random error occurred.")
            println(it)
        }.catch { println("some error occurred") }
        .collect()
}


fun emit() = flow {
    for (i in 1..10) {
        emit(i)
    }
}
This will print "1 2 3 4" and stop. I'd like to print every number except number 5. (I'm doing this to simulate a random error, i know that in this specific case i could filter out the number 5).
a
Restart, yes, resume, no. By the time you receive the exception, the state of the flow was already torn down. There's nowhere to resume from.
b
humm, that's unfortunate. I'll try another aproach. Thanks
@Adam Powell when you say restart, you're refering to "retry" function?
a
I think so? Sorry, I'm not sure of the specific operator function but I'm going by how flow itself works 🙂 once
.collect
resumes with an exception all of the associated state from that collection is gone
so catching and retrying is the best such an operator function can do
b
oh i see. i'm creating a flow of possibly infinite events, so it's on a
while(true)
loop. So i think that the retry operator is good enough to restart the loop. Thanks again
s
FWIW: Sounds like you really want to use
SharedFlow
or
StateFlow