Skip to content

Instantly share code, notes, and snippets.

@ismailbenhallam
Created March 26, 2023 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismailbenhallam/4ce537954a2e1dd22bee806c8c1409de to your computer and use it in GitHub Desktop.
Save ismailbenhallam/4ce537954a2e1dd22bee806c8c1409de to your computer and use it in GitHub Desktop.
package coroutines
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.http.HttpResponse.BodyHandler
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
private suspend fun main() = runBlocking {
val client = HttpClient.newHttpClient()
val request = HttpRequest.newBuilder(URI("https://example.com/")).GET().build()
launch { sendRequestAndPrintResultSuspendable(client, request) }
println(">> We don't have to wait for the response..")
}
suspend fun sendRequestAndPrintResultSuspendable(client: HttpClient, request: HttpRequest) =
coroutineScope {
launch(Dispatchers.IO) {
val response = client.sendSuspendable(request, HttpResponse.BodyHandlers.ofString())
response.run {
println("from ${Thread.currentThread().name}")
println("Status code: ${statusCode()}");
println("Headers: ${headers().allValues("content-type")}");
println("Body: ${body().take(15)}...");
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun <T> HttpClient.sendSuspendable(request: HttpRequest, bodyHandler: BodyHandler<T>): HttpResponse<T> {
return suspendCoroutine { continuation ->
sendAsync(request, bodyHandler).whenComplete { response, exception ->
if (exception == null) {
continuation.resume(response)
} else {
continuation.resumeWithException(exception)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment