如何通过改型和协程暂停处理错误

时间:2019-08-06 03:11:48

标签: android kotlin retrofit coroutine

我使用rxjava构建了我的应用程序,需要转换为协程进行后台工作,我需要帮助才能看到使用翻新版2.6.0和协程的实际示例以及适当的错误处理方法

我尝试为改型创建通用错误处理程序,并为加载身份验证错误的网络资源状态创建包装器

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))
        }


    }



}

我的ViewModelClass

       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)
                }
        }
    }
}

0 个答案:

没有答案