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

zak.taccardi

09/10/2020, 8:43 PM
given a
Job
, how can I fail it with an exception? I want to cancel it abnormally so its parent fails
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 8:46 PM
“fail without an exception” is basically the definition of “cancellation”. Cancellation is failure without an exception, or failure with a
CancellationException
, and cancellation is just failure with an exception. They all use the same mechanism, just different words to describe different special cases.
z

zak.taccardi

09/10/2020, 8:48 PM
yeah, that’s the problem. trying to have it fail, not just cancel
basically just trying to implement this:
Copy code
private fun Job.fail() {
    TODO("make this job fail with an exception")
}
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 8:49 PM
job.cancel(RuntimeException("fail"))
?
z

zak.taccardi

09/10/2020, 8:49 PM
that doesn’t actually compile anymore
only non-deprecated/hidden API for cancellation is
Copy code
fun cancel(cause: CancellationException? = null)
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 8:52 PM
ugh, right, i always forget that. So
job.cancel(CancellationException(RuntimeException("fail")))
z

zak.taccardi

09/10/2020, 8:56 PM
this seemed to do the trick, lol
Copy code
private fun CoroutineScope.fail() {
     try {
         runBlocking(this.coroutineContext) {
             @Suppress("RedundantAsync", "IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION")
             async(this@fail.coroutineContext) {
                 error("bad things!!")
             }
                 .await()
         }
     } catch (exception: IllegalStateException) {
     }
 }
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 9:02 PM
I mean, if you really just want to cancel the parent, just get the parent job and cancel it
I have no idea what that code does haha
if you have to try that hard, i feel like it’s a sign something else is wrong
z

zak.taccardi

09/10/2020, 9:02 PM
writing tests lol
not production code haha
z

Zach Klippenstein (he/him) [MOD]

09/10/2020, 9:04 PM
I mean, tests are production code in that they are committed, they will probably outlast you, and other people have to maintain them – “it’s just tests” is no reason to write over-complicated code
z

zak.taccardi

09/10/2020, 9:07 PM
I don’t feel this is too complicated. Just trying to write tests for the code I wrote, which requires a
job.fail()
function rather than
job.cancel()
4 Views