How do I use a Kotlin Deferred (Coroutine) object in Java?

Viewed 1423

I have some Java code which at some point needs to pause and wait for a result. I am trying to solve this problem using Kotlin Coroutines.

The async method of BuilderKt allows me to pass the work off to the background successfully. But I'm unclear on how to do a non-blocking wait for the result.

Here is how I setup the work (and get a Deferred):

Deferred<T> deferred = BuildersKt.async(GlobalScope.INSTANCE, Dispatchers.getIO(), CoroutineStart.DEFAULT, new Function2<CoroutineScope, Continuation<? super T>, T>() {
    @Override
    public T invoke(CoroutineScope coroutineScope, Continuation<? super T> continuation) {
        return /* Do some work and return a T */;
    }
});

The part I'm having trouble with is the await requires a continuation and returns nothing

deferred.await(new Continuation<T>() {
    @NotNull
    @Override
    public CoroutineContext getContext() {
        return ???;
    }

    @Override
    public void resumeWith(@NotNull Object o) {
        ???
    }

});

If I can't make it do a non-blocking await, I would need to keep polling to check if it's complete which is obviously not the right approach. What pieces of this puzzle am I missing?

The Kotlin documentation has no examples on how to use it with Java and there's no useful javadoc for the methods in the continuation

0 Answers
Related