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

tapac

10/20/2019, 6:47 PM
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

Adam Powell

10/20/2019, 7:08 PM
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

tapac

10/20/2019, 8:41 PM
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

octylFractal

10/20/2019, 8:53 PM
just do the above, and if you need to wrap it in another
async {}
block, do so.
t

tapac

10/20/2019, 9:15 PM
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

octylFractal

10/20/2019, 9:40 PM
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

Dico

10/21/2019, 2:20 AM
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.
4 Views