简体   繁体   中英

How to resume a Kotlin Coroutine Continuation in Java

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM