https://kotlinlang.org logo
Title
b

Bruno Ortiz

11/11/2020, 7:08 PM
Is the a way to resume a flow on error?
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

Adam Powell

11/11/2020, 7:10 PM
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

Bruno Ortiz

11/11/2020, 7:13 PM
humm, that's unfortunate. I'll try another aproach. Thanks
@Adam Powell when you say restart, you're refering to "retry" function?
a

Adam Powell

11/11/2020, 7:26 PM
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

Bruno Ortiz

11/11/2020, 7:28 PM
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

Shalom Halbert

11/12/2020, 11:02 AM
FWIW: Sounds like you really want to use
SharedFlow
or
StateFlow