Is there any simple way to implement `Deferred` in...
# coroutines
t
Is there any simple way to implement
Deferred
interface? I was trying to delegate that interface to an instance returned by
async
function, but it doesn't work well.
Copy code
class MyDeferred<T>(val original: Deferred<T>) : Deferred<T> by original

MyDeferred(async{ ...} )
I want to be able to call some code on async completition or execption, maybe there is another way?
a
what are you trying to do more specifically?
if you control the code inside the
async {}
block,
Copy code
async {
  try {
    stuff()
  } finally {
    codeToRunOnCompletion()
  }
}
if you don't,
Copy code
try {
  theDeferred.await()
} catch (e: TheExceptionThrown) {
  doStuffWith(e)
}
since many things may
.await()
on a Deferred and respond when the underlying async is done
t
I want to make function which will return Deferred with provided fcuntion. That deferred should execute function and then do some additional work on complete or another code on exception. Like
Copy code
fun <T>  executeAsync(body: ()->T) : MyDeferred<T> {
}
I want to allow users to use all standard functions which works with Deferred like
awaitAll
o
just do the above, and if you need to wrap it in another
async {}
block, do so.
t
I want to have
special
extension for
MyDeferred
which will chain executions and execute additional code only once.
Copy code
fun <T, R> MyDeferred<T>.and(body: (T) -> R) : MyDeferred<R>
o
why not just:
Copy code
suspend fun <T, R> Deferred<T>.and(body: suspend (T) -> R) = async { body(await()) }
really sounds like you want a Flow though
d
You can also just do
deferred.invokeOnCompletion { .... }
Doesn't seem like the right tool for your use case
Coroutines are designed explicitly to avoid the pattern that you're trying to create and use
If you want to have
map
and all those operators, you can indeed use
Flow
or you can even use Java's
CompletableFuture
. You can add the
kotlinx-coroutines-jdk8
as a dependency and call
Deferred.asCompletableFuture()
I think.