SHARE
TWEET

Untitled

a guest May 20th, 2019 161 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class CoroutineResultExceptionViewModel(
  2.     private val service: CoroutineExampleService,
  3.     private val converter: Converter<ResponseBody, ServiceException>
  4. ) : CoroutineScope, ViewModel() {
  5.  
  6.   private val job: Job = Job()
  7.  
  8.   override val coroutineContext: CoroutineContext
  9.     get() = Dispatchers.Main + job
  10.  
  11.   init {
  12.     launch {
  13.       try {
  14.         try {
  15.           getResources().forEach(::println)
  16.         } catch (exception: ServiceException) {
  17.           if (exception.code == "ERROR_USER_NOT_LOGGED_IN") throw UserLoggedOutException(exception)
  18.           else throw exception
  19.         }
  20.       } catch (exception: UserLoggedOutException) {
  21.         exception.printStackTrace()
  22.       }
  23.     }
  24.   }
  25.  
  26.   private suspend fun getResources(): List<ResourcesList> {
  27.     val response: Response<List<ResourcesList>> = service
  28.         .resources()
  29.         .await()
  30.  
  31.     val body: List<ResourcesList>? = response.body()
  32.     if (body != null) {
  33.       return body
  34.     }
  35.  
  36.     val errorBody: ResponseBody = response.errorBody() ?: throw MissingErrorBodyException()
  37.     throw converter.convert(errorBody) ?: EmptyConversionException(errorBody)
  38.   }
  39.  
  40.   override fun onCleared() {
  41.     super.onCleared()
  42.     job.cancel()
  43.   }
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top