https://kotlinlang.org logo
#codereview
Title
# codereview
d

Dalinar

02/01/2019, 6:06 AM
anyone know how to migrate this code from https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md ?
Copy code
fun <T> future(context: CoroutineContext = CommonPool, block: suspend () -> T): CompletableFuture<T> =
        CompletableFutureCoroutine<T>(context).also { block.startCoroutine(completion = it) }

class CompletableFutureCoroutine<T>(override val context: CoroutineContext) : CompletableFuture<T>(), Continuation<T> {
    override fun resumeWith(result: Result<T>) {
        result
                .onSuccess { complete(it) }
                .onFailure { completeExceptionally(it) }
    }
}
suspend fun <T> CompletableFuture<T>.await(): T =
        suspendCoroutine { cont: Continuation<T> ->
            whenComplete { result, exception ->
                if (exception == null) // the future has been completed normally
                    cont.resume(result)
                else // the future has completed with an exception
                    cont.resumeWithException(exception)
            }
        }
I mean, is it correct apart from the
CommonPool
part? should I just replace
CommonPool
with
EmptyCoroutineContext
?
g

gildor

02/03/2019, 2:44 PM
Why do you use custom future implementation instead of provided by kotlinx.coroutines java8 adapter? This implementation from KEEP is just an example if you want to use in own code, ai would just use kotlinx.coroutines
d

Dalinar

02/03/2019, 2:46 PM
that's part of my old code , i removed it in my new code but currently that part is shelved - so it get it to compile i still have that there
g

gildor

02/03/2019, 2:46 PM
Also empty coroutine context doesn't have sense in this case
Do you use Kotlinx.coroutines?
d

Dalinar

02/03/2019, 2:46 PM
i just upgraded to 1.0,1 last week
g

gildor

02/03/2019, 2:47 PM
If so,just use Dispatcher.Default to make it work instead of common pool
d

Dalinar

02/03/2019, 2:47 PM
ok i will try that, thanks
g

gildor

02/03/2019, 2:48 PM
But I would just remove this function and use kotlinx.coroutines future with structured concurrency https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-jdk8/kotlinx.coroutines.future/kotlinx.coroutines.-coroutine-scope/future.html
8 Views