【发布时间】:2019-06-11 12:09:15
【问题描述】:
您如何正确地使用Retrofit 和Coroutines 测试Http 请求/响应?
我正在使用最新的Retrofit 版本:2.6.0,它支持suspend 功能。
编辑
我还提供了一些易于实现的代码:
API接口
@GET
suspend fun getCountriesListAsync(@Url url: String): Response<ArrayList<Country>>
一些存储库
suspend fun makeCountryApiCallAsync(): Response<ArrayList<Country>> =
treasureApi.getCountriesListAsync(COUNTRIES_API_URL)
在ViewModel上的实现:
private suspend fun makeCountriesApiCall() {
withContext(Dispatchers.Main) {
switchProgressBarOn()
}
try {
val countriesListResponse = setupRepository.makeCountryApiCallAsync()
if (countriesListResponse.isSuccessful) {
withContext(Dispatchers.Main) {
switchProgressOff()
countriesList.value = countriesListResponse.body()
}
} else {
withContext(Dispatchers.Main) {
showErrorLayout()
}
}
} catch (e: Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
showErrorLayout()
}
}
}
【问题讨论】:
标签: android retrofit2 android-testing kotlin-coroutines