Skip to content Skip to sidebar Skip to footer

How To Call Kotlin Suspending Coroutine Function From Java 7

I'm trying to call Kotlin function from Java 7. I'm using coroutines and this called function is suspending, for example: suspend fun suspendingFunction(): Boolean { return asy

Solution 1:

You have several options depending on your environment.

  1. If you are using RxJava2 in the project, the module kotlinx-coroutines-rx2 has utility functions to convert back and forth between coroutines and Rx datatypes.

Example

suspendfunsayHello(): String {
    delay(1000)
    return"Hi there"
}

funsayHelloSingle(): Single<String> = GlobalScope.rxSingle { sayHello() }
  1. Otherwise, you could add a new Continuation class that matches the definition of the old one and is also useful in the Java side.

Example (Kotlin side)

abstractclassContinuation<in T> : kotlin.coroutines.Continuation<T> {
    abstractfunresume(value: T)abstractfunresumeWithException(exception: Throwable)overridefunresumeWith(result: Result<T>) = result.fold(::resume, ::resumeWithException)
}   

Example (Java side)

sayHello(newContinuation<String>() {
    @OverridepublicCoroutineContextgetContext() {
        returnEmptyCoroutineContext.INSTANCE;
    }

    @Overridepublicvoidresume(String value) {
        doSomethingWithResult(value);
    }

    @OverridepublicvoidresumeWithException(@NotNull Throwable throwable) {
        doSomethingWithError(throwable);
    }
});

Solution 2:

You can use BuildersKt. That is already included in the implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"

    BuildersKt.launch(
            GlobalScope.INSTANCE,
            (CoroutineContext) Dispatchers.getMain(),
            CoroutineStart.DEFAULT,
            (Function2<CoroutineScope, Continuation<? superUnit>, Unit>) (coroutineScope, continuation) -> {
                // your code herereturnUnit.INSTANCE;
            }
    );

Post a Comment for "How To Call Kotlin Suspending Coroutine Function From Java 7"