https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bnn

11/29/2019, 4:03 AM
I’m wondering wether it’s good to use runCatching inside suspend function. It’s something like below.
Copy code
suspend fun foo(): Foo {
    return runCatching {
        // do something with calling other suspend functions
        Foo()
    }.getOrElse { exception ->
        // do somethiing
        Foo()
    }
}
The code example above will not propagate CancellationException to caller. Is it OK? Or would I better to consider propagate CancellationException, like
Copy code
suspend fun foo(): Foo {
    return runCatching {
        // do something with calling other suspend functions
        Foo()
    }.getOrElse { exception ->
        if (exception is CancellationException) {
            throw exception
        }
        // do something
        Foo()
    }
}
In my opinion, suspend functions are better to propagate CancellationException. But, when we use runCatching inside it, there might be kind of boilerplate like above. Are there idiomatic ways to handle coroutines cancellation with runCatching. Or should I avoid to use it inside suspend function?
p

pg

12/03/2019, 11:49 AM
You can write something like runCancellableCatching (need naming engineer) which will rethrow exception when cancellation exception appear or behave like runCatching block if not
10 Views