What’s the current best practice to expose deferre...
# coroutines
s
What’s the current best practice to expose deferreds (primarily) and suspendable functions to Java APIs. I’d prefer to not require a separate API like RxJava, but as far as I can tell reactivestreams doesn’t have a Single type, and the CompleteableFuture integration doesn’t support lazy coroutines.
And specifically regarding the CompletableFutures, pretty sure there’s a pretty bad problem with Deferreds that have a
start = CoroutineStart.LAZY
:
Copy code
val deferred = scope.async(start = CoroutineStart.LAZY) { "hello" }
val future = deferred.asCompletableFuture()

future.get() // Not sure this will actually cause the deferred to be evaluated
e
For a project i just used when having to handle with
CompletableFuture
Copy code
future{
 
}.await(()
o
I presume the reason that
asCompletableFuture()
doesn't work with LAZY is the same reason that the
scope.future
call says:
Copy code
* A value of [CoroutineStart.LAZY] is not supported
 * (since `CompletableFuture` framework does not provide the corresponding capability) and
 * produces [IllegalArgumentException].
I don't know if it would be as good if
asCompletableFuture()
just failed, since you could still manually
start()
the deferred in kotlin... but maybe it deserves some documentation
s
My solution was to wrap the CompletableFuture in a lazy:
Copy code
val foo by lazy { scope.future { something.await() } }
I think that gets the correct behavior
In that the future will eagerly start the coroutine, but only when it’s needed