小编fre*_*uks的帖子

如何处理改造和协程挂起的错误

我用 rxjava 构建了我的应用程序,需要转换为协程以进行后台工作我需要帮助才能看到使用改造 2.6.0 和协程的实际示例以及正确的错误处理方法,提前致谢

我尝试创建一个通用的错误处理程序进行改造,并为 Loading Authenticated Error 的网络资源状态创建一个包装器

class AuthRepository @Inject constructor(val authApi: AuthApi) {

    suspend fun Loginauth(email:String,password:String)= liveData {
        emit(AuthResource.loading(null))
        try{
            val response=authApi.login(email,password)
            if (response.isSuccessful){
                emit(AuthResource.authenticated(response.body()))
            }
            emit(AuthResource.error(response.message(),null))
        }catch (e:Throwable){
            Log.d("any","error occured ${e.message}")
         emit(AuthResource.error(e.message!!,null))
        }catch (e:HttpException){
            Log.d("any","error http error${e.message}")
            emit(AuthResource.error(e.message!!,null))
        }


    }



}
Run Code Online (Sandbox Code Playgroud)

我的视图模型类

       screenState.value= AuthResource.loading(null)
        viewModelScope.launch {
            val source=authRepository.Loginauth(email!!,password!!)
            screenState.addSource(source){
             AuthResource.authenticated(it)
                screenState.removeSource(source)
                if (it.status == AuthResource.AuthStatus.ERROR){
                    screenState.removeSource(source)
                    AuthResource.error(it.message!!,null)
                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin retrofit

7
推荐指数
0
解决办法
2060
查看次数

标签 统计

android ×1

coroutine ×1

kotlin ×1

retrofit ×1