Hello, I would like to replace RxJava with Kotlin ...
# coroutines
t
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
But outer block shouldn’t be cancelled.
Cancelled child doesn’t cancel parent
t
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
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
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
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
Thank you. When exception propagated is not needed, I will use Coroutines in a way that does not rethrow CancelationException.
g
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