Hello. I have a question about combining coroutine...
# coroutines
k
Hello. I have a question about combining coroutines and
Result<T>
. I have the code like following:
Copy code
launch {
    runCatching { doSomething() }
        .onSuccess {
            doSuccessProcess(it)
        }
        .onFailure {
            doFailureProcess()
        }
}
I wanna handle errors if
doSomething()
fails. But this code catches
CancellationException
as well when
launch
was canceled. Are there any problems? Can I just ignore the
CancellationException
?
g
But what should happen in case of cancellation?
it looks for me as valid behavior
you requested for some result, cancellation means that result is not ready
k
oh, I see. you’re right. I want to just ignore the result if it canceled.
btw, does it not impede the propagation of cancellations?
g
how you can do that in theory?
You can do something like this of course to ignore:
Copy code
runCatching { 
try { doSomething() } catch (e: CancellationException) { someDefault() }
}
also, I don’t see reason in general for this usage of runBlocking with launch, you do not return any result, why not just use try/catch, so you can check exception type
k
doSomething()
returns value and it may throw exceptions too. And I can’t list up those exceptions in advance.
g
Not sure what you mean, I meant this:
Copy code
try {
  doSomething()
} catch(e: CancellationException) {
   //Do nothning
} catch(e: Exception) {
  doFailureProcess()
}
k
doSomething returns value, so I meant:
Copy code
val value = try {
  doSomething()
} catch (e: CancellationException) {
  return
} catch (e: Exception) {
  doFailureProcess()
  return
}
doSuccessProcess(value)
Yes, try/catch style is possible, but I prefer Result<T> style because it is more readable than try/catch one. My question was "CancellationException will be caught by runCatching", and you did let me notice that it is a surely exception because it was cancelled so I need handle the exception. So the question was already solved. I am always grateful for your help!
g
👍