我有以下使用协程在后台执行网络抓取的代码
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。
发布于 2019-06-30 21:17:17
似乎我需要将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)
}
}我将我的showResult更改为挂起函数,这样它就可以包含withContext(Dispatchers.Main)
private suspend fun showResult(result: String) {
withContext(Dispatchers.Main) {
// Code that show the result
}
}https://stackoverflow.com/questions/56824898
复制相似问题