最近,我通过跟踪这个kotlin-coroutine
来学习CodeLabs教程。在进行了一些操作之后,我想知道是否可以在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中使用协同工作呢?
发布于 2020-04-16 14:29:42
关于Java问题中的协同,请查看关于stackOverflow的这个问题。
--但在我看来,,可以使用其他异步调用工具(,例如RXjava)。你会被召回的,但我想会没事的。
但是要注意,不要使用AsyncTask,因为现在已经不再推荐了。
发布于 2021-03-26 10:37:21
对于简单的后台任务,我建议使用异步类可运行。
示例呼叫:
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
)
另一种方法是使用一个真正的线程,您可以动态创建这个线程,或者创建一个类并从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();
https://stackoverflow.com/questions/61252550
复制相似问题