【问题标题】:Can't catch network error when using coroutine, but the error could be caught in RxJava 2. What did I miss?使用协程时无法捕获网络错误,但可以在 RxJava 2 中捕获该错误。我错过了什么?
【发布时间】:2019-11-11 11:23:08
【问题描述】:

我有以下代码使用协程在后台执行网络获取

    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。

【问题讨论】:

    标签: android kotlin rx-java2 okhttp3 kotlin-coroutines


    【解决方案1】:

    似乎我需要将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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 2016-12-30
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      相关资源
      最近更新 更多