[英]Android how to use Kotlin-Coroutine in Java?
最近我正在按照这个CodeLabs 教程学习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;
}
并在我的片段中调用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 问题中的协程,请在 stackOverflow 上查看此问题。
但在我的拙见中,使用其他工具进行异步调用(例如 RXjava )。 你会受到回调的影响,但我认为这会很好。
但请注意不要使用AsyncTask ,因为它现在已弃用。
快乐编码
对于简单的后台任务,我建议使用异步 class Runnable 。
示例调用:
mRunnable = Runnable {
// May or may not run on the UI Thread, depending on the way you call the Handler.
}
Handler mHandler = new Handler();
// Run it using "mHandler.run()". Or run it delayed:
mHandler.postDelayed(
mRunnable, // Runnable
1000 // Delay in milliseconds
)
替代方法是使用一个真正的线程,您可以动态创建它,或者创建一个 class 并从 Thread 继承:
Thread thread = new Thread() {
@Override
public void run() {
try {
// Does not run on UI thread (non-blocking)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.