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

takahirom

09/18/2018, 2:04 AM
Hello, I would like to replace RxJava with Kotlin coroutine. I wrote it in RxJava as follows.
Copy code
kotlin
    api.fetchPersons()
        .subscribeOn(scheduler)
        .subscribe(
            { persons ->
              showPersons(persons)
            },
            { e ->
              showErrorDialog(e)
            })
I enclosed with try catch to do the same on kotlin coroutines as follows. But in this case CancellationException did not go to parents job, so I thought that it would be in an invalid state. Even if CancellationException is caught by the user, the outer block is not just canceled, is there no problem? Is it fine just like this?
Copy code
kotlin
    launch { 
      try {
        val persons = api.fetchPersons() // suspend function
        showPersons(persons)
      } catch (e: Throwable) {
        showErrorDialog(e)
      }
    }
g

gildor

09/18/2018, 2:49 AM
But outer block shouldn’t be cancelled.
Cancelled child doesn’t cancel parent
t

takahirom

09/18/2018, 3:29 AM
Thank you.
Canceled child does not cancel parent
I had a misunderstanding. I still do not know if it is safe to catch CancelationException. Do I need to take this form?
Copy code
launch {
    try {
        val persons = api.fetchPersons() // suspend function
        showPersons(persons)
    } catch (cancellationException: CancellationException) {
        throw cancellationException
    } catch (e: Throwable) {
        showErrorDialog(e)
    }
}
g

gildor

09/18/2018, 4:41 AM
Why do you want to rethrow CancelationException in this case? CancellationException is just a marker exception propagated and cancels coroutine, but not a coroutine parent. In your particular example I don’t see why you need this with your code.
t

takahirom

09/19/2018, 2:15 AM
Sorry for late. Does
cancels coroutine
mean throwing CancelationException?
Copy code
val job = launch {
    try {
        delay(Int.MAX_VALUE) // cancel here
    } catch (e: CancellationException) {
        e.printStackTrace()
    }
}
job.cancel()
g

gildor

09/19/2018, 3:10 AM
Yes, delay will throw cancellationexception (but probably in you case job will be cancelled even before delay, you just call it too early, add small delay before
.cancel()
) and you need it only if you somehow want handle this case
t

takahirom

09/19/2018, 6:05 AM
Thank you. When exception propagated is not needed, I will use Coroutines in a way that does not rethrow CancelationException.
g

gildor

09/19/2018, 8:09 AM
To be clear. Main difference, that if you caught Cancellation exception and didn't rethrow, your coroutine handles this and will be finished for parent coroutine, otherwise parent coroutine. But if you parent coroutine is cancelled itself it never return even if suspend function is not cancel