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

louiscad

01/26/2018, 4:35 PM
Hi! I have a non suspending function that has a callback where errors are received, and I want any incoming error to stop the coroutine it may have been launched in. My code currently looks like this: 1️⃣
Copy code
fun SomeReceiver.someFunction(parentJob: Job) {
    someNonSuspendingCode()
    setOnErrorListener { errorCode ->
        parentJob.cancel(SomeException(errorCode))
    }
}
I'm wondering if I should make it a
suspend fun
so I can get the current job from the coroutineContext (currently available in the intrisics package) and remove this not so nice (IMHO)
parentJob
parameter. If I did, it'd look like this: 2️⃣
Copy code
suspend fun SomeReceiver.someFunction() {
    val currentJob = coroutineContext[Job]!!
    someNonSuspendingCode()
    setOnErrorListener { errorCode ->
        currentJob.cancel(SomeException(errorCode))
    }
}
e

elizarov

01/26/2018, 6:58 PM
I’d go with suspend fun
👍🏽 1
6 Views