https://kotlinlang.org logo
Title
s

spierce7

11/15/2018, 10:06 PM
Is there any way to re-run a coroutine automatically without putting it in a while loop, or will I have to wait for cold streams for something like that? I'm trying to build in some automatic error handling, and if a coroutine errors out due to something like a network exception, a common behavior would be that the user can select that the request would be re-run.
g

gildor

11/16/2018, 2:19 AM
Not sure that cold streams could make something with it. I would write just special version of await that supports retry for network exceptions for you http library
so it can be or special coroutine adapter (so will work also as suspend function) or just an abstraction over common await()
e

elizarov

11/16/2018, 7:01 AM
You are looking for something like this?
inline fun rerunAutomatically(block: () -> Unit) { 
    while (true) {
        runCatching { block() }.onFailure { handleException(it) }
    }
}
You can use it like this:
launch { 
    rerunAutomatically { /* your code here */ } 
}
g

gildor

11/16/2018, 7:18 AM
Yes, this what I want to say. Usually such retry functions are more sophisticated and used for particular use cases. Like you want to retry http request only for specific http codes, or you want to retry IO only when you have particular errors, not any IOException
And coroutines actually allow to write them easily and add support of delay, exponential backoff etc
l

louiscad

11/16/2018, 11:52 AM
Exactly, that's why Andrey Breslav favorite Kotlin feature (as of KotlinConf 2018) is functions, because they are so simple but allow so much, including such use cases for otherwise complex error handling.
l

littlelightcz

11/19/2018, 1:02 PM
I like to use Failsafe lib for retry logic (not only with coroutines)