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

matej

10/05/2017, 5:06 PM
to bridge the gap with a legacy system
e

elizarov

10/05/2017, 5:32 PM
What kind of legacy is that? If this legacy is using
CompletableFuture
then it will not fly on API level < 24 anyway.
m

matej

10/05/2017, 5:32 PM
It's just using the Future interface
e

elizarov

10/05/2017, 5:33 PM
I’m puzzled. How one cause use future interface? It is a completely useless interface for any kind of async programming
The only thing you an do with a future, is invoke its blocking
get
function
m

matej

10/05/2017, 5:34 PM
or cancel it
from what I can see that's what it was used for mostly
e

elizarov

10/05/2017, 5:34 PM
Anyway, you can easily write your own wrapper that implements a
Future
interface on top of a
Deferred
. To implement
get
use
runBlocking { deferred.await() }
, the
cancel
just delegate, etc.
m

matej

10/05/2017, 5:35 PM
yup, I started doing exactly that
I'm just a bit stuck on the semantics of cancel
and mayInterruptIfRunning
wondering how to implement honoring that flag in the most straightforward way possible
preferably without introducing extra state that already isn't in Deferrable
of course I could do it with a flag and invokeOnCompletion
but that seems somehow dirty
e

elizarov

10/05/2017, 5:37 PM
There is no way to honor it. Just ignore it
m

matej

10/05/2017, 5:37 PM
OK
that works too 😄
so, a naive implementation would look like this
Copy code
class DeferredFuture<T>(private val deferred: Deferred<T>) : Future<T> {

    override fun isCancelled() = deferred.isCancelled

    override fun cancel(mayInterruptIfRunning: Boolean) = deferred.cancel()

    override fun isDone() = !deferred.isActive

    override fun get() = runBlocking { deferred.await() }

    override fun get(timeout: Long, unit: TimeUnit?) = runBlocking {
        withTimeout(timeout, unit!!) { deferred.await() }
    }
}
sorry, don't know how to format in threads
e

elizarov

10/05/2017, 5:46 PM
Yes. Format as usual with three backticks
It should work. A hint, though: when you declare
override fun get(timeout: Long, unit: TimeUnit?)
remove the question mark from
unit
type and you will not have to use double-bang
m

matej

10/05/2017, 5:54 PM
fantastic, thanks again for the help
4 Views