读完本期How to deal with exception和这个媒介Android Networking in 2019 — Retrofit with Kotlin’s Coroutines我创建了我的解决方案,其中包含一个 BaseService
,能够进行改造调用并将结果和异常沿着“链”转发:
API
@GET("...")
suspend fun fetchMyObject(): Response<List<MyObject>>
基础服务
protected suspend fun <T : Any> apiCall(call: suspend () -> Response<T>): Result<T> {
val response: Response<T>
try {
response = call.invoke()
} catch (t: Throwable) {
return Result.Error(mapNetworkThrowable(t))
}
if (!response.isSuccessful) {
return Result.Error...
}
return Result.Success(response.body()!!)
}
child 服务
suspend fun fetchMyObject(): Result<List<MyObject>> {
return apiCall(call = { api.fetchMyObject() })
}
repo 协议(protocol)
suspend fun myObjectList(): List<MyObject> {
return withContext(Dispatchers.IO) {
when (val result = service.fetchMyObject()) {
is Result.Success -> result.data
is Result.Error -> throw result.exception
}
}
}
注意:有时我们需要的不仅仅是抛出异常或一种类型的成功结果。为了处理这些情况,我们可以这样做:
sealed class SomeApiResult<out T : Any> {
object Success : SomeApiResult<Unit>()
object NoAccount : SomeApiResult<Unit>()
sealed class Error(val exception: Exception) : SomeApiResult<Nothing>() {
class Generic(exception: Exception) : Error(exception)
class Error1(exception: Exception) : Error(exception)
class Error2(exception: Exception) : Error(exception)
class Error3(exception: Exception) : Error(exception)
}
}
然后在我们的 ViewModel 中:
when (result: SomeApiResult) {
is SomeApiResult.Success -> {...}
is SomeApiResult.NoAccount -> {...}
is SomeApiResult.Error.Error1 -> {...}
is SomeApiResult.Error -> {/*all other*/...}
}
有关此方法的更多信息 here .
BaseViewModel
protected suspend fun <T : Any> safeCall(call: suspend () -> T): T? {
try {
return call()
} catch (e: Throwable) {
parseError(e)
}
return null
}
ChildViewModel
fun fetchMyObjectList() {
viewModelScope.launch {
safeCall(call = {
repo.myObjectList()
//update ui, etc..
})
}
}
我认为ViewModel
(或BaseViewModel
)应该是处理异常的层,因为UI决策逻辑就在这一层,例如,如果我们只是想要显示 toast 、忽略某种类型的异常、调用另一个函数等等...
你觉得怎么样?
编辑:我创建了一个 medium就这个话题
最佳答案
I think the ViewModel (or a BaseViewModel) should be the layer handling the exceptions, because in this layer lies the UI decision logic, for example, if we just want to show a toast, ignore a type of exception, call another function etc...
What do you think?
当然,你是对的。即使逻辑位于 Repository
/Service
中,协程也应在 ViewModel
上触发。这就是为什么 Google 创建了一个名为 viewModelScope 的特殊 coroutineScope
。 ,否则它将是“repositoryScope”。协程在异常处理方面还有一个很好的功能,称为 CoroutineExceptionHandler。这就是事情变得更好的地方,因为您不必实现 try{}catch{}
block :
val coroutineExceptionHanlder = CoroutineExceptionHandler{_, throwable ->
throwable.printStackTrace()
toastLiveData.value = showToastValueWhatever()
}
稍后在ViewModel
coroutineScope.launch(Dispatchers.IO + coroutineExceptionHanlder){
val data = serviceOrRepo.getData()
}
当然你仍然可以使用try/catch
block 而不使用CoroutineExceptionHandler
,自由选择。
请注意,如果使用 Retrofit,您不需要 Dispatchers.IO
调度程序,因为 Retrofit 会为您执行此操作(自 Retrofit 2.6.0 起)。
无论如何,我不能说这篇文章不好,但它不是最好的解决方案。如果您想遵循文章指南,您可能需要查看Transformations on the LiveData .
编辑:
您需要更多了解的是,协程并不安全。我的意思是,它们可能会导致内存泄漏,尤其是在 Android 的整个生命周期中。您需要一种在 Activity
/Fragment
不再存在时取消协程的方法。由于 ViewModel
具有 onCleared
(当 Activity
/Fragment
被销毁时调用),这意味着协程应该向其中之一开火。也许这就是您应该在 ViewModel 中启动协程的主要原因。请注意,使用 viewModelScope
无需取消
作业onCleared
。
一个简单的例子:
viewModelScope.launch(Dispatchers.IO) {
val data = getDataSlowly()
withContext(Dispatchers.MAIN) {
showData();
}
}
或者没有viewModelScope
:
val job = Job()
val coroutineScope = CoroutineContext(Dispatchers.MAIN + job)
fun fetchData() {
coroutineScope.launch() {
val data = getDataSlowly()
withContext(Dispatchers.MAIN) {
showData();
}
}
}
//later in the viewmodel:
override fun onCleared(){
super.onCleared()
job.cancel() //to prevent leaks
}
否则,您的Service
/Repository
将会泄漏。另一个注释是NOT to use the GlobalScope
在这种情况下。
关于android - 协程和改造,处理错误的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083309/