Recently I am learning kotlin-coroutine
by following this CodeLabs tutorial. After some hands on, I was wondering if I could the same code in java.
So first I wrote a simple kotlin code in MyKotlinFragment.kt
file like this:
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;
}
And called myKotlinDemo()
in my fragment; it works.
Next I opended a java file named MyCoroutineFragment.java
in the same project but I can't make it work.
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,
}
I can't convert the first file into Java. How can I fix this?
If it is impossible to convert, why and how else can I use coroutine in Java?