coroutine for retrofit in activity
class MainActivity : AppCompatActivity(), CoroutineScope {
override val coroutineContext = Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch {
findViewById<TextView>(R.id.text).text = withContext(Dispatchers.IO) { get() }
findViewById<View>(R.id.progress).visibility = View.INVISIBLE
}
}
fun get(): String?{
return Retrofit.Builder()
.baseUrl("http://www.mocky.io")
.build()
.create(Network::class.java)
.get()
//.error()
.execute()
.body()?.string() ?: "errore"
}
}
interface Network {
@GET("/v2/5d0f88043200005c00dc6a47?mocky-delay=5s")
fun get(): Call<ResponseBody>
@GET("/v2/5d0f895a3200003900dc6a4d?mocky-delay=5s")
fun error(): Call<ResponseBody>
}