Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CoroutineResultExceptionViewModel(
- private val service: CoroutineExampleService,
- private val converter: Converter<ResponseBody, ServiceException>
- ) : CoroutineScope, ViewModel() {
- private val job: Job = Job()
- override val coroutineContext: CoroutineContext
- get() = Dispatchers.Main + job
- init {
- launch {
- try {
- try {
- getResources().forEach(::println)
- } catch (exception: ServiceException) {
- if (exception.code == "ERROR_USER_NOT_LOGGED_IN") throw UserLoggedOutException(exception)
- else throw exception
- }
- } catch (exception: UserLoggedOutException) {
- exception.printStackTrace()
- }
- }
- }
- private suspend fun getResources(): List<ResourcesList> {
- val response: Response<List<ResourcesList>> = service
- .resources()
- .await()
- val body: List<ResourcesList>? = response.body()
- if (body != null) {
- return body
- }
- val errorBody: ResponseBody = response.errorBody() ?: throw MissingErrorBodyException()
- throw converter.convert(errorBody) ?: EmptyConversionException(errorBody)
- }
- override fun onCleared() {
- super.onCleared()
- job.cancel()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement