Last active
June 29, 2018 02:50
-
-
Save TomoyaShibata/44bb9c64aa3ff3d6aced049e72c1519b to your computer and use it in GitHub Desktop.
Kotlin Coroutines でリトライをしながら通信を試行する with RxJava 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = [email protected]() | |
[email protected](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