Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package coroutinestest
- import kotlinx.coroutines.experimental.runBlocking
- import okhttp3.*
- import java.io.IOException
- import kotlin.coroutines.experimental.suspendCoroutine
- object Coroutines {
- private val client = OkHttpClient()
- private val request = Request.Builder()
- .url("http://whatismyip.com/")
- .build()
- private suspend fun asyncGet(reqNumber: Int) = suspendCoroutine<Response?> { continuation ->
- println("Sending request $reqNumber")
- client.newCall(request).enqueue(object : Callback {
- override fun onFailure(call: Call?, e: IOException?) {
- continuation.resumeWithException(e ?: RuntimeException("Error occured!"))
- }
- override fun onResponse(call: Call?, response: Response?) {
- println("Received response for $reqNumber")
- continuation.resume(response)
- }
- })
- }
- @JvmStatic
- fun main(args: Array<String>) {
- val requestsCount = 3
- runBlocking {
- val responses = (1..requestsCount)
- .map { asyncGet(it)?.body()?.string() ?: "" }
- .joinToString("")
- println("Total length: ${responses.length}")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment