I have a following kotlin class
class KotlinClass() {
suspend fun executeSuspend(): ResultClass {
.....
}
}
I want to call this suspend function from a Java class.
public class JavaClass {
public void process() {
// .... Existing code
ResultClass result;
// Initialize result class by calling suspend function
// Use the result data
process(result)
}
}
I know that a suspend function can be called from another suspend function or coroutine scope.
I can start a Coroutine using a runBlocking and call the execute function from there like this.
class KotlinClass() {
fun execute(): ResultClass {
return runBlocking {executeSuspend() }
}
suspend fun executeSuspend(): ResultClass {
.....
}
}
And I will call execute function from JavaClass.
But the problem here is that the runBlocking will block the underlying thread.
I don’t want to block any thread while calling the executeSuspend function. I want the thread to wait but in a suspended form.
My executeSuspend is not a launch and forget task. So I cannot call it from a launch. I also cannot put all the subsequent processes in the java class inside one single Coroutine scope.
Can someone please tell me how can I call the executeSuspend function and wait for the result without blocking the underlying thread.
I have tried runBlocking. It blocks the underlying thread.
I have tried CoroutineScope.async. It doesn’t block the underlying thread but it can be called from another suspend function or coroutine scope. So doesn’t fit my use case.
Tushar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.