Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin Coroutines でリトライをしながら通信を試行する with RxJava 2
package com.example.tomoyashibata.myapplication
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.rx2.rxSingle
import java.net.URL
import kotlin.coroutines.experimental.suspendCoroutine
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch(UI) {
try {
val bitmap = this@MainActivity.loadAvatarImage()
this@MainActivity.avatarImageView.setImageBitmap(bitmap)
} catch (e: Exception) {
// エラーを Toast で表示
Toast.makeText(this@MainActivity, e.toString(), Toast.LENGTH_LONG).show()
}
}
}
private suspend fun loadAvatarImage(): Bitmap = suspendCoroutine { cont ->
// URL から末尾の .jpg を取り除いてわざとエラーが起こるようにしている
val urlConnection = URL("https://pbs.twimg.com/profile_images/637494283365298177/J0t3qvlm_400x400").openConnection()
rxSingle(CommonPool) {
urlConnection.connect()
val stream = urlConnection.getInputStream()
return@rxSingle BitmapFactory.decodeStream(stream)
}
.retry(10)
.subscribe({
cont.resume(it)
}, {
cont.resumeWithException(it)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment