Kotlin suspend function not executing after delay when called from Java

Viewed 356

I am trying to call this Kotlin suspend code from my Java class. The solution is based on what is mentioned here. https://stackoverflow.com/a/52887677/5140533

Kotlin Code:

Main.kt

suspend fun doWorld() = coroutineScope {
    launch {
        println("Thread name2 ${Thread.currentThread().name}")
        delay(2000L)
        println("Hello world")
    }
}
@OptIn(DelicateCoroutinesApi::class)
fun doSomethingAsync() =
    GlobalScope.future { doWorld() }

Converter.java

public class Converter {
    public static void main(String[] args) {
       MainKt.doSomethingAsync();
    }
}

When I call doSomethingAsync() from my Java class, I do not see any of the print statements. Can somebody please explain what exactly is going on and how I can correct this.

1 Answers

I think in your case the program completes before a new coroutine starts. Try to delay the current Main Thread in the main function after calling MainKt.doSomethingAsync():

public class Converter {
    public static void main(String[] args) {
       MainKt.doSomethingAsync();
       try {
            TimeUnit.MILLISECONDS.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Or use MainKt.doSomethingAsync().get()
    }
}

Then I guess the logs will be displayed.

Related