Is there any way to re-run a coroutine automatical...
# coroutines
s
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
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
You are looking for something like this?
Copy code
inline fun rerunAutomatically(block: () -> Unit) { 
    while (true) {
        runCatching { block() }.onFailure { handleException(it) }
    }
}
You can use it like this:
Copy code
launch { 
    rerunAutomatically { /* your code here */ } 
}
g
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
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
I like to use Failsafe lib for retry logic (not only with coroutines)