Guest User

Untitled

a guest
Dec 12th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.28 KB | None | 0 0
  1. package coroutinestest
  2.  
  3. import kotlinx.coroutines.experimental.runBlocking
  4. import okhttp3.*
  5. import java.io.IOException
  6. import kotlin.coroutines.experimental.suspendCoroutine
  7.  
  8.  
  9. object Coroutines {
  10.  
  11.     private val client = OkHttpClient()
  12.  
  13.     private val request = Request.Builder()
  14.             .url("http://whatismyip.com/")
  15.             .build()
  16.  
  17.     private suspend fun asyncGet(reqNumber: Int) = suspendCoroutine<Response?> { continuation ->
  18.  
  19.         println("Sending request $reqNumber")
  20.  
  21.         client.newCall(request).enqueue(object : Callback {
  22.             override fun onFailure(call: Call?, e: IOException?) {
  23.                 continuation.resumeWithException(e ?: RuntimeException("Error occured!"))
  24.             }
  25.  
  26.             override fun onResponse(call: Call?, response: Response?) {
  27.                 println("Received response for $reqNumber")
  28.                 continuation.resume(response)
  29.             }
  30.         })
  31.     }
  32.  
  33.     @JvmStatic
  34.     fun main(args: Array<String>) {
  35.         val requestsCount = 3
  36.  
  37.         runBlocking {
  38.             val responses = (1..requestsCount)
  39.                     .map { asyncGet(it)?.body()?.string() ?: "" }
  40.                     .joinToString("")
  41.  
  42.             println("Total length: ${responses.length}")
  43.         }
  44.  
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment