Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.38 KB | None | 0 0
  1. typealias ResultCallback<T> = ((T) -> Unit)
  2.  
  3. interface UseCase<TResult> {
  4.  
  5.     var callback: ResultCallback<TResult>?
  6.  
  7.     fun action(): TResult
  8.  
  9.     fun execute(callback: ResultCallback<TResult>) {
  10.  
  11.         this.callback = callback
  12.  
  13.         val result = action()
  14.  
  15.         this.callback?.invoke(result)
  16.     }
  17.  
  18.     fun cancel() {
  19.  
  20.         callback = null
  21.     }
  22. }
  23.  
  24. class CoroutineUseCase<T>(
  25.     usecase: UseCase<T>,
  26.     private val context: CoroutineContext
  27. ) : UseCase<T>  by usecase {
  28.  
  29.     override fun execute(callback: ResultCallback<T>) {
  30.  
  31.         this.callback = callback
  32.  
  33.         val result = runBlocking(context) {
  34.             this@CoroutineUseCase.action()
  35.         }
  36.  
  37.         this.callback?.invoke(result)
  38.     }
  39. }
  40.  
  41. fun <T> UseCase<T>.executeIoCoroutine(callback: ResultCallback<T>) = CoroutineUseCase(this, Dispatchers.IO).execute(callback)
  42.  
  43.  
  44. class GetHoroscopeUseCase(
  45.     private val sunsign: String
  46. ) : UseCase<HoroscopeDto> {
  47.  
  48.     var _callback: ResultCallback<HoroscopeDto>? = null
  49.     override var callback: ResultCallback<HoroscopeDto>?
  50.         get() = _callback
  51.         set(value) {
  52.             _callback = value
  53.         }
  54.  
  55.     override fun action() = App.INSTANCE.horoscopeApi.getHoroscope(sunsign).execute().let { response ->
  56.         if (response.isSuccessful) response.body()!!
  57.         else throw IllegalArgumentException()
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement