to bridge the gap with a legacy system
# coroutines
m
to bridge the gap with a legacy system
e
What kind of legacy is that? If this legacy is using
CompletableFuture
then it will not fly on API level < 24 anyway.
m
It's just using the Future interface
e
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
or cancel it
from what I can see that's what it was used for mostly
e
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
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
There is no way to honor it. Just ignore it
m
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
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
fantastic, thanks again for the help