4

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?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Qazi Fahim Farhan
  • 2,066
  • 1
  • 14
  • 26

2 Answers2

3

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
MustafaKhaled
  • 1,343
  • 9
  • 25
-2

For simple background tasks, I recommend using the async class Runnable.

Example call:

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
)

Alternative would be to use a real thread, which you can create on the fly, or create a class and inherit from 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();
KYL3R
  • 3,877
  • 1
  • 12
  • 26