Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
How to ignore JobCancellationException?

Recently, I've upgraded Kotlin Coroutines from experimental to 1.1.1 and faced the problem that job.cancel() in new version works differently.

Here's the code with Experimental Coroutines:

fun <R : Any, T : Deferred<R>> T.runAsync(
        job: Job,
        onSuccess: (result: R) -> Unit,
        onFailed: (errorMsg: String?) -> Unit) {
    launch(UI, parent = job) {
        try {
            val result = this@runAsync.await()
            onSuccess(result)
        } catch (e: Exception) {
            onFailed(e.message)
        }
    }
}

Here's with 1.1.1:

fun <R : Any, T : Deferred<R>> T.runAsync(
        job: Job,
        onSuccess: (result: R) -> Unit,
        onFailed: (errorMsg: String?) -> Unit) {
    GlobalScope.launch(Dispatchers.Main + job) {
        try {
            val result = withContext(Dispatchers.IO) {
                this@runAsync.await()
            }
            onSuccess(result)
        } catch (e: Exception) {
            onFailed(e.message)
        }
    }
}

For example:

My fragment destroyed and called job.cancel() during coroutine is running.

In experimental coroutines neither onSuccess() nor onFailed() will be called.

In 1.1.1: onFailed() called because caught of JobCancellationException

I figured out to add catch (e: JobCancellationException), but it's impossible:

/**
 * @suppress **This an internal API and should not be used from general code.**
 */
internal expect class JobCancellationException(

So, the question is: How to handle/ignore JobCancellationException ?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You try to catch the super-class CancellationException instead, which is a part of the public API.

Do note that if something throws CancellationException you are generally expected to rethrow it so upstream objects are notified about the cancellation. See Cancellation is Cooperative

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda