Home > front end >  How to resume a Kotlin Coroutine Continuation in Java
How to resume a Kotlin Coroutine Continuation in Java

Time:10-20

I am adding Kotlin code to a Java project. I created a Kotlin suspend function with suspendCancellableCoroutine

suspend fun someSuspendFunction = suspendCancellableCoroutine<Boolean>{ continuation ->
     someJavaObject.someSuspendFunctionContinuation = continuation
}

I need someSuspendFunction to resume by some logic done in someJavaObject so I declare a field in someJavaObject to store the continuation for later use.

CancellableContinuation<Boolean> someSuspendFunctionContinuation;

However, when I want to resume it, I can't find a proper method to call. In Kotlin I can simply call continuation.resume(true). I looked into the definition of resume() and found it called resumeWith(Result.success(value)). So I tried to write this in Java:

someSuspendFunctionContinuation.resumeWith(Result.Companion.success(true))

which gives this error: 'success(java.lang.Boolean)' has private access in 'kotlin.Result.Companion'

So I tried to construct Result directly

someSuspendFunctionContinuation.resumeWith(new Result(true));

This gives me : Expected 0 arguments but found 1

Is it possible to construct a Result with value to reusme a coroutine continuation in Java?

CodePudding user response:

You can create a Result object using reflection:

public void resume() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    var successMethod = Result.Companion.getClass().getDeclaredMethod("success", Object.class);
    successMethod.setAccessible(true);

    someSuspendFunctionContinuation.resumeWith(successMethod.invoke(Result.Companion, true));
}

But I think it is better to just create yourself a very small util in Kotlin for using it in Java:

fun <T> resumeContinuationWithSuccess(cont: Continuation<T>, value: T) {
    cont.resumeWith(Result.success(value))
}
public void resume() {
    SuspendUtils.resumeContinuationWithSuccess(someSuspendFunctionContinuation, true);
}
  • Related