简体   繁体   English

等待 Kotlin 协程导致 Java

[英]Wait for Kotlin Coroutines result in Java

I would like rewrite all AsyncTask to Kotlin Coroutines .我想将所有AsyncTask重写为Kotlin Coroutines Call and wait for result from Coroutines in Java code.Coroutines代码中调用并等待协Java的结果。 For example: I have some long time consumable method in Kotlin .例如:我在Kotlin有一些长时间的消耗方法。

Kotlin: Kotlin:

class Coroutines {
     suspend fun readFile(): String {
         return GlobalScope.async {
            read long file...
          }.await()
     }
}

Now, i would like to wait (but no block UI thread) for complete method, ideally without a callbacks.现在,我想等待(但没有阻塞 UI 线程)完成方法,理想情况下没有回调。

Java: Java:

public class MainActivity extends AppCompatActivity {
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        Coroutines c = new Coroutines();
        c.readFile(); //Wait for result but no block UI thread
    }
}

Basically a coroutine suspend function can only be called from another suspend function or from coroutines builder like async or launch.基本上,协程挂起 function 只能从另一个挂起 function 或协程构建器(如异步或启动)调用。 Since java doesn't have the support for coroutine,you can't launch it from java code.由于 java 不支持协程,因此无法从 java 代码启动它。

But mix of both can be possible, for example you can create a viewmodel with live data which gets updated from coroutine launched form viewModelScope.但是两者的混合是可能的,例如,您可以使用从协程启动的表单 viewModelScope 更新的实时数据创建一个视图模型。 The result or progress can be observed in activity/fragment.可以在活动/片段中观察结果或进展。

Hope this helps you.希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM