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

igor.wojda

02/14/2019, 4:00 PM
Hey I am getting
JobCancellationException
and I am not sure what is the reason. My only hypothesis is that I am starting and canceling multiple times function that is in suspended state 🤔 but honestly I am not sure… Can somebody throw more light on this? What is the reason for throwing this exception?
l

louiscad

02/14/2019, 5:57 PM
@igor.wojda Do you use channels with offer or poll, or do you use async without a local wrapping
coroutineScope { ... }
for structured concurrency?
i

igor.wojda

02/15/2019, 10:19 AM
@louiscad I am running coroutime like this:
Copy code
val job:Job? = null
fun getQuote() {
    job?.cancel()

    job CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
        delay(300)
        val result = repository.getQuote()
    }
}

class Repository(val retrofitQuoteService:RetrofitQuoteService) {
    suspend fun getQuote() {
        retrofitQuoteService.getQuoteAsync().await()
    }
}
getQuote
can be called multiple times as this is called while user types in text input - called each time text input changes
l

louiscad

02/15/2019, 11:03 AM
@igor.wojda Your
getQuote()
suspend function throws if there's a network issue or an unsuccessful response received. You need to catch it at call site (here, a `try`/`catch` in your
launch
block).
BTW, for general knowledge, you can (should) ask it on StackOverflow, post the link here, and I'll anwser it.
i

igor.wojda

02/15/2019, 11:21 AM
This is simplified version of the code - the problem is that requests are 100% correct here (all return 200) and data is parsed correctly on each single call. This problem arrises only when
getQuote
function is called multiple times (I sniff underlying network requests and they are correct), so I try to understand the reason behind it. Also
JobCancellationException
is as internal class so I cannot catch this exception explicitly. I need to get to core of this and understand why this happens.
l

louiscad

02/15/2019, 11:26 AM
@igor.wojda No, network can fail which throws. A
JobCancellationException
is always the sign of an uncaught exception, usually happening in a
launch
or
async
block.
b

bdawg.io

02/15/2019, 4:26 PM
A
JobCancellationException
is thrown when you cancel the job via
job.cancel()
Where are you "getting JobCancellationException"? Is it in your logs as an uncaught exception? The
delay
inside of your
launch
block will throw that exception if the job is cancelled before your function resumes to your repository
12 Views