Skip to content

Instantly share code, notes, and snippets.

@venator85
Created November 12, 2019 16:55
Show Gist options
  • Save venator85/67e0b4c4ed13997aeffffbf43a09d097 to your computer and use it in GitHub Desktop.
Save venator85/67e0b4c4ed13997aeffffbf43a09d097 to your computer and use it in GitHub Desktop.
Coroutine Samples
// implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
// for lifecycleScope: implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-rc02'
class MyFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val request = Request.Builder().get()
.url("https://icanhazip.com")
.build()
// blocking style
viewLifecycleOwner.lifecycleScope.launch {
try {
val result = exampleBlockingStyle(request)
Log.e("result: $result", this)
} catch (e: Exception) {
e.printStackTrace()
}
}
// listener style
viewLifecycleOwner.lifecycleScope.launch {
try {
val result = exampleListenerStyle(request)
Log.e("result: $result", this)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
suspend fun exampleBlockingStyle(req: Request): String? {
return withContext(Dispatchers.IO) {
Log.d("execute on " + Thread.currentThread().name, this)
val response = OkHttpClient().newCall(req).execute()
Thread.sleep(3000)
if (response.isSuccessful) {
response.body()?.string()
} else {
throw IOException("HTTP error ${response.code()}")
}
}
}
suspend fun exampleListenerStyle(req: Request): String? {
return suspendCoroutine { continuation ->
OkHttpClient().newCall(req).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
val body = response.body()?.string()
continuation.resume(body)
}
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment