https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Marko Kovacevic

11/21/2020, 8:34 PM
[CompletableFuture] I’m having issues converting CompletableFuture to a suspendable function as there aren’t any examples nor guides for it. Does someone know what is the proper way to handle this? I’m using the Java 11 Http client and creating a wrapper for calling an API.
Copy code
suspend fun HackerNewsApi.fetchItem(id: Int): CompletableFuture<HttpResponse<String>> {
    return client.sendAsync(
        request("${this.domain}/v0/item/$id.json"),
        HttpResponse.BodyHandlers.ofString()
    )
}
n

nfrankel

11/21/2020, 9:25 PM
Copy code
suspend fun HackerNewsApi.fetchItem(id: Int): HttpResponse<String> {
    return client.sendAsync(
        request("${this.domain}/v0/item/$id.json"),
        HttpResponse.BodyHandlers.ofString()
    ).asDeferred().await()
}
d

Dariusz Kuc

11/21/2020, 10:52 PM
no need to convert to deferred, you can just use await extension function directly on the future (from https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-jdk8/)
👍 2