使用kotlin协程处理retrofit 2.6的无互联网连接错误

Mus*_*Ojo 5 android kotlin retrofit2 kotlin-coroutines

我正在使用 Retrofit 2.6 和 kotlin 协程来进行 API 调用,而不阻塞 UI 线程,我让它工作了,但是当我关闭互联网连接时应用程序崩溃了。logcat 错误为:E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1

这是我的代码:

private fun handleIntent(slug: String) {
    val service = UtilityMethods.migrationTimeService()

    UtilityMethods.showView(loading_view)
    UtilityMethods.hideView(network_error_msg)

    CoroutineScope(Dispatchers.IO).launch {
        val res = service.getPostBySlug(slug)

            try {
                withContext(Dispatchers.Main) {

                    //Do something with response e.g show to the UI.
                    val post = res.body()!!.first()

                    UtilityMethods.hideView(loading_view)

                    val title = post.title?.rendered
                    val content = post.content?.rendered
                    val imageUrl = post.jetPackFeaturedMediaUrl

                    title_txtView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        Html.fromHtml(title, Html.FROM_HTML_MODE_COMPACT).toString()
                    else
                        Html.fromHtml(title).toString()

                    content_txtView.loadData(content.toString(), "text/html", "UTF-8")

                    Picasso.get().load(imageUrl).fit().centerCrop().into(thumbnail_imgview)
                }

            } catch (e: HttpException) {
                UtilityMethods.showView(network_error_msg)
            } catch (e: Throwable) {
                Toast.makeText(this@PostContentActivity, "Ooops: Something else went wrong", Toast.LENGTH_LONG)
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

而不是这个:

    CoroutineScope(Dispatchers.IO).launch {
    val res = service.getPostBySlug(slug)

        try {
            withContext(Dispatchers.Main) {
Run Code Online (Sandbox Code Playgroud)

试试这个:

    CoroutineScope(Dispatchers.Main).launch {
    val res = service.getPostBySlug(slug)

        withContext(Dispatchers.IO) {
            try {
Run Code Online (Sandbox Code Playgroud)

将“try and catch”块代码包装在 Dispatchers.IO 中,而不是将 Dispatchers.IO 包装在 try 块中