最近我正在按照这个 CodeLabs tutorial 学习 kotlin-coroutine
。经过一些实践后,我想知道我是否可以在 java 中编写相同的代码。
所以首先我在 MyKotlinFragment.kt
文件中编写了一个简单的 kotlin 代码,如下所示:
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
// ... some codes
private fun myKoroutineDemo(){
GlobalScope.launch {
val result1:Int = foo();
val result2:Int = bar();
val result3 = result1 + result2;
Log.e(TAG, ""+result3);
}
}
suspend fun foo():Int{
delay(2000);
var result = 2+2;
delay(500);
return result;
}
suspend fun bar():Int{
delay(2000);
var result = 7-2;
delay(500);
return result;
}
并在我的 fragment 中调用了myKotlinDemo()
;它有效。
接下来,我在同一个项目中打开了一个名为 MyCoroutineFragment.java
的 java 文件,但我无法使其工作。
import kotlinx.coroutines.delay;
import kotlinx.coroutines.launch; // delay and launch imports arenot fount and so they are red
private suspend int foo(){ return 2 + 2; }
// the `suspend` keyword is not found by android studio, same with the bar method
private void myCoroutineDemo(){
// GlobalScope.launch don't show up here,
}
我无法将第一个文件转换为 Java。我该如何解决这个问题?
如果无法转换,为什么以及如何在 Java 中使用协程?
最佳答案
对于 Java 中的协程问题,请检查 this question on stackOverflow .
但以我的拙见,请使用其他工具进行异步调用(例如 RXjava)。你会遭受回调的困扰,但我认为不会有什么问题。
但请注意不要使用 AsyncTask,因为它现已已弃用。
关于java - Android如何在Java中使用Kotlin-Coroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61252550/