https://kotlinlang.org logo
Title
g

gildor

10/09/2017, 6:22 AM
ioContext
probably not the best alias for CommonPool, because if you want to use rxjava scheduler analogue you should name it
computationContext
. Just because use CommonPool for blocking IO operations is bad idea
Instead of
val task = async(ioContext) { dataProvider.loadData("Task") }
    val result: Result<String> = task.await()
you can use
val result: Result<String>  = run(ioContext) { dataProvider.loadData("Task") }
You can also use Sealed classes to implement
Result
with better and API and avoid nullable fields
d

Dmytro Danylyk

10/10/2017, 4:28 AM
Thanks. Changed ioContext to bgContext and added some explanation about implementation.
As for sealed class, in this case I will have to make Success class generic.
So instead if nullability check I will end up with type check (is Success, is Error)
And about run. I don't like using it, because if you wrap run with try-cath, cancel job, code inside run can still crash your app.
g

gildor

10/10/2017, 4:54 AM
why do not return Result from
dataProvider.loadData("Task")
?
because your app still crashes on
async.await()
call, I don’t see difference with
run
in your example
But you can have Sealed with generic - https://github.com/gildor/kotlin-coroutines-retrofit/blob/master/src/main/kotlin/ru/gildor/coroutines/retrofit/Result.kt#L10 I think Sealed class is better not because use type check instead of null check, but because you can pass this Result class of particular type or save it to (for example you can have something like
fun processError(result: Result.Error)
. Also, you can have more complicated Sealed class with additional helper methods and combinators.
d

Dmytro Danylyk

10/10/2017, 8:49 AM
https://github.com/dmytrodanylyk/coroutine-recipes/blob/master/app/src/main/java/com/dmytrodanylyk/exception/trycatch/MainActivity.kt#L93 Steps with `async`: 1. Call
startPresenting
2. Call
stopPresenting
3. You will see stack trace with cancellation exception Exactly same code but with
run
1. Call
startPresenting
2. Call
stopPresenting
3. You will see stack trace with cancellation exception 4. In 5 sec app crash with
IllegalStateException("Ooops you are unlucky")
g

gildor

10/10/2017, 8:52 AM
do you pass context to
run
? because run by default uses context of parent coroutine
d

Dmytro Danylyk

10/10/2017, 8:54 AM
Yes
run doesn’t have default dispatcher
g

gildor

10/10/2017, 8:58 AM
of course, by default run uses parent context (with dispatcher or without), but you can specify it
I will check your example later when will have time
oh, you are right about default context, you still should pass it, otherwise there is no reason to use run
but still not sure why you have this error with cancelled run, should check