如何在Java中使用Kotlin的Deferred(协程)对象?

huangapple 未分类评论45阅读模式
标题翻译

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

问题

以下是翻译好的内容:

我有一些 Java 代码,在某个点上需要暂停并等待结果。我正在尝试使用 Kotlin 协程来解决这个问题。

BuilderKt 的 async 方法成功地将工作传递到后台。但是我不清楚如何进行非阻塞等待结果。

以下是我设置工作(并获得 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 /* 做一些工作并返回 T */;
    }
});

我遇到问题的部分是,await 方法需要一个 continuation,并且不返回任何内容:

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

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

如果我不能使其进行非阻塞等待,我将需要不断轮询以检查是否完成,这显然不是正确的方法。我缺少这个难题的哪些部分?

Kotlin 文档中没有关于如何在 Java 中使用它的示例,并且这些 continuation 方法的 javadoc 也没有什么有用的信息。

英文翻译

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&lt;T&gt; deferred = BuildersKt.async(GlobalScope.INSTANCE, Dispatchers.getIO(), CoroutineStart.DEFAULT, new Function2&lt;CoroutineScope, Continuation&lt;? super T&gt;, T&gt;() {
    @Override
    public T invoke(CoroutineScope coroutineScope, Continuation&lt;? super T&gt; 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&lt;T&gt;() {
    @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

huangapple
  • 本文由 发表于 2020年3月16日 22:50:15
  • 转载请务必保留本文链接:https://java.coder-hub.com/60708150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定