Android how to use Kotlin-Coroutine in Java?

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. Can anyone show me how to fix this?

If it is impossible to convert, why and how else can I use coroutine in java? I am open to all solutions.

Answer

For coroutines in Java question, check this question on stackOverflow.

But in my hummble opinion, use other tools for asynchronous call (e.g. RXjava). You gonna suffer from callbacks but I think it will be fine.

But be aware not to use AsyncTask as it’s now deprecated.

Happy coding 🤓

Leave a Reply

Your email address will not be published. Required fields are marked *