`I’m integrating one Sdk in my android Java project. In that Sdk they are having kotlin with suspend function. That I can’t call from my Java class as it forcing me to add continuation as param. I have searched many things but I couldn’t get clear idea to achieve. I have added continuation interface in my class and passing that instance to suspend method but the resumewith function is not calling. My question can we call suspend function from java directly. if not how can we achieve it by using like rx java or CompletableFuture. Please help me to find the solution. Thanks in advance.
Asked
Active
Viewed 304 times
1 Answers
0
To call a Kotlin suspend function from Java, we can use CompletableFuture
.
Add below dependency on gradle:
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1"
}
Suppose you have a Kotlin suspend function getUserData()
defined like this:
Kotlin:
suspend fun getUserData(userId: String): UserData {
// perform some long-running operation to get user data
return userData
}
And you want to call this function from Java using CompletableFuture
. Here's how you can do it:
public CompletableFuture<UserData> getUserData(String userId) {
CompletableFuture<UserData> future = new CompletableFuture<>();
Continuation<UserData> continuation = new Continuation<UserData>() {
@Override
public void resume(UserData result) {
future.complete(result);
}
@Override
public void resumeWithException(Throwable exception) {
future.completeExceptionally(exception);
}
};
// call the Kotlin suspend function using the Kotlin coroutines API
getUserData(userId, continuation);
return future;
}