Tushar
Tushar

Reputation: 1

How to call a suspend function of a kotlin class from a java class without blocking the underlying thread

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.

Upvotes: 0

Views: 73

Answers (1)

broot
broot

Reputation: 28432

Short answer: you can't. This is the whole/main point of coroutines to make this possible. If it would be possible in Java, coroutines wouldn't exist.

In traditional programming, the only way to wait inside a method is by blocking the thread. If we can't block the thread, we have to use alternatives: background threads, futures, callbacks, etc. By using such techniques we can solve any problem that we can solve by using coroutines. It will just require to design our application differently.

Upvotes: 1

Related Questions