协程和改造,处理错误的最佳方式

Gui*_*lhE 23 android kotlin kotlin-android-extensions retrofit2 kotlin-coroutines

在阅读了这个问题如何处理异常和这个2019 年的中型Android 网络 - 使用 Kotlin 的协程改造后,我创建了我的解决方案,其中包括BaseService能够进行改造调用并将结果和异常转发到“链”中:

应用程序接口

@GET("...")
suspend fun fetchMyObject(): Response<List<MyObject>>
Run Code Online (Sandbox Code Playgroud)

基本服务

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()!!)
}
Run Code Online (Sandbox Code Playgroud)

儿童服务

suspend fun fetchMyObject(): Result<List<MyObject>> {
    return apiCall(call = { api.fetchMyObject() })
}
Run Code Online (Sandbox Code Playgroud)

回购

    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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:有时我们需要的不仅仅是抛出异常或一种类型的成功结果。为了处理这些情况,我们可以通过以下方式实现:

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)
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后在我们的 ViewModel 中:

when (result: SomeApiResult) {
    is SomeApiResult.Success -> {...}
    is SomeApiResult.NoAccount -> {...}
    is SomeApiResult.Error.Error1 -> {...}
    is SomeApiResult.Error -> {/*all other*/...}
}
Run Code Online (Sandbox Code Playgroud)

在此处详细了解此方法。

基础视图模型

protected suspend fun <T : Any> safeCall(call: suspend () -> T): T? {
    try {
        return call()
    } catch (e: Throwable) {
        parseError(e)
    }
    return null
}
Run Code Online (Sandbox Code Playgroud)

子视图模型

fun fetchMyObjectList() {
    viewModelScope.launch {
        safeCall(call = {
            repo.myObjectList()
            //update ui, etc..
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为 the ViewModel(or a BaseViewModel) 应该是处理异常的层,因为在这一层中存在 UI 决策逻辑,例如,如果我们只想显示吐司,忽略一种类型的异常,调用另一个函数等等......

你怎么认为?

编辑:我用这个主题创建了一个媒体

cor*_*her 13

我认为ViewModel(或BaseViewModel)应该是处理异常的层,因为在这一层是UI决策逻辑,例如,如果我们只想显示一个toast,忽略一种类型的异常,调用另一个函数等。 ..

你怎么认为?

当然,你是对的。ViewModel即使逻辑在Repository/ 中,协程也应该触发Service。这就是为什么谷歌已经创建了一个特殊的coroutineScope叫做viewModelScope,否则它会是 "repositoryScope" 。协程还有一个很好的异常处理特性,称为CoroutineExceptionHandler. 这是事情变得更好的地方,因为您不必实现try{}catch{}块:

val coroutineExceptionHanlder = CoroutineExceptionHandler{_, throwable -> 
    throwable.printStackTrance()
    toastLiveData.value = showToastValueWhatever()
}
Run Code Online (Sandbox Code Playgroud)

后来在 ViewModel

coroutineScope.launch(Dispatchers.IO + coroutineExceptionHanlder){
      val data = serviceOrRepo.getData()
}
Run Code Online (Sandbox Code Playgroud)

当然你仍然可以使用try/catch没有 的块CoroutineExceptionHandler,自由选择。

请注意,在 Retrofit 的情况下,您不需要Dispatchers.IO调度程序,因为 Retrofit 为您完成了这项工作(自 Retrofit 2.6.0 起)。

无论如何,我不能说这篇文章不好,但它不是最好的解决方案。如果您想遵循文章指南,您可能需要检查LiveData 上的转换

编辑:您需要了解更多的是协程不安全。我的意思是它们可能会导致内存泄漏,尤其是在整个 Android 生命周期中。您需要一种在Activity/Fragment不再存在时取消协程的方法。由于ViewModel具有onCleared(在Activity/Fragment被销毁时调用),这意味着协程应该在其中之一中触发。也许这就是您应该在ViewModel. 请注意,viewModelScope无需cancel工作onCleared

一个简单的例子:

viewModelScope.launch(Dispatchers.IO) {
   val data = getDataSlowly()
   withContext(Dispatchers.MAIN) {
      showData();
   }
} 
Run Code Online (Sandbox Code Playgroud)

或没有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
}
Run Code Online (Sandbox Code Playgroud)

否则,您的Service/Repository会泄漏。另一个注意事项是在这种情况下不要 使用GlobalScope

  • 该活动将只保存视图模型的引用并说:“myViewModel.fetchMyObjectList()”不是挂起而是作为方法。然后在“fetchMyObjectList()”中,您可以只使用“viewModelScope.launch”。是的,如果你有 Retrofit 2.6+ 并且你的协程中只有改造调用,则不需要 `withContext(Dispatchers.IO)` (2认同)