lundi 26 décembre 2022

Can I invoke a Kotlin coroutine from Java reflectively and wrap it in CompletableFuture?

I'm reflectively accessing a Kotlin class and trying to invoke a coroutine, wrapping it in a CompletableFuture. Looking at an example from Spring, they manage to wrap such a reflective call in a Mono using kotlinx-coroutines-reactor:

Mono<Object> mono = MonoKt.mono(Dispatchers.getUnconfined(), (scope, continuation) ->
                        KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

I could easily just call Mono#toFuture() but I'm trying to avoid dragging in a dependency to Reactor. Can I achieve the same without going through Mono?

Looking at kotlinx-coroutines-jdk8, there seems to exist something similar to the above, but I can't figure out how to use it. Perhaps:

CompletableFuture<Object> future = FutureKt.future(
         GlobalScope.INSTANCE, Dispatchers.getUnconfined(), CoroutineStart.DEFAULT, (scope, continuation) ->
                KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

But this is just a blind guess, as I have next to 0 Kotlin knowledge. Are CoroutineStart.DEFAULT or GlobalScope.INSTANCE even ok here?

Btw, how is Spring getting away with passing a CoroutineDispatcher (Dispatchers.getUnconfined()) where a CoroutineContext is expected?





Aucun commentaire:

Enregistrer un commentaire