android - 使用协程时无法捕获网络错误,但可以在 RxJava 2 中捕获该错误。我错过了什么?
问题描述
我有以下代码使用协程在后台执行网络获取
try {
networkJob = CoroutineScope(Dispatchers.IO).launch {
val result = fetchOnBackground(searchText)
withContext(Dispatchers.Main) {
showResult("Count is $result")
}
}
} catch (exception: Throwable) {
showResult(exception.localizedMessage)
}
当网络在那里时,一切都很好。但是,当主机不正确或没有网络时,它就会崩溃。catch
抓不住了
当我使用 RxJava 编码时
disposable = Single.just(searchText)
.map{fetchOnBackground(it)}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ showResult("Count is $it") },
{ showResult(it.localizedMessage) })
一切正常。即使在没有网络的情况下,错误也会在错误回调中被捕获。
我在协程代码中错过了什么,在使用协程时我无法捕捉到错误?
注意:网络抓取使用的是 OkHttp。
解决方案
好像我需要try-catch
把CouroutineScope(Dispatchers.IO).launch
networkJob = CoroutineScope(Dispatchers.IO).launch {
try {
val result = fetchOnBackground(searchText)
showResult("Count is $result")
} catch (exception: Throwable) {
showResult(exception.localizedMessage)
}
}
我将 my 更改showResult
为暂停功能,以便它可以包含withContext(Dispatchers.Main)
private suspend fun showResult(result: String) {
withContext(Dispatchers.Main) {
// Code that show the result
}
}
推荐阅读
- c++ - MFC:如何根据按钮单击交替显示两个组框?
- qt - 如何在 Qt 中调用框架
- java - 如何使用java将文件的内容保存为单个字符串
- python - 客户端离开时减少线程数
- vue.js - 电容写入文件到下载文件夹
- sql-server - 从表中删除“Document No_”到“Document No_”的记录?
- cdo-climate - 在 cdo 中使用双线性插值重新网格化 NetCDF 文件
- csv - 如何在perl中删除不可打印的字符^@
- mongodb - 无法从 Intellij Idea Ultimate/DataGrip 连接到 mongo atlas
- asp.net-mvc - Asp.Net MVC 在一个视图中显示两个表