没有 exception/error 当没有 internet coroutine + retrofit

No exception/error when no internet coroutine + retrofit

我有以下设置

服务

// ItunesService
suspend fun searchItunesPodcast(@Query("term") term: String): Response<PodcastResponse>

存储库

// ItunesRepo
override suspend fun searchByTerm(term: String) = withContext(ioDispatcher) {
    return@withContext itunesService.searchItunesPodcast(term)
}

视图模型

fun searchPodcasts(term: String) {
        viewModelScope.launch {
            _res.value = Result.loading()
            try {
                val response = itunesRepo.searchByTerm(term)
                if (response.isSuccessful) { // Nothing from here when no internet
                    _res.value = Result.success(response.body())
                } else {
                    _res.value = Result.error(response.errorBody().toString())
                }
            } catch (e: Exception) {
                _res.value = Result.exception(e)
            }
        }
    }

一切正常,直到我关闭测试设备上的移动 data/internet。 _res 值停留在加载状态。我试过在没有互联网的情况下在 if (response.isSuccessful) 添加断点,但它看起来像 val response = itunesRepo.searchByTerm(term) 从来没有 returns 我该如何解决这个问题

我在 Repository

上改用 Flow api
override suspend fun searchPodcasts(term: String) = flow {
        emit(Result.Loading)
        try {
            val res = itunesService.searchItunesPodcast(term)
            if (res.isSuccessful)
                emit(Result.Success(res.body()))
            else
                emit(Result.Error("Generic error: ${res.code()}"))
        } catch (e: Exception) {
            emit(Result.Error("Unexpected error", e))
        }
    }.flowOn(ioDispatcher)

然后在我的 ViewModels 上收集结果