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

kawmra

04/24/2019, 7:02 AM
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

gildor

04/24/2019, 7:04 AM
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

kawmra

04/24/2019, 7:14 AM
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

gildor

04/24/2019, 7:30 AM
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

kawmra

04/24/2019, 9:42 AM
doSomething()
returns value and it may throw exceptions too. And I can’t list up those exceptions in advance.
g

gildor

04/24/2019, 9:45 AM
Not sure what you mean, I meant this:
Copy code
try {
  doSomething()
} catch(e: CancellationException) {
   //Do nothning
} catch(e: Exception) {
  doFailureProcess()
}
k

kawmra

04/24/2019, 11:55 AM
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

gildor

04/24/2019, 12:43 PM
👍
3 Views