Advertisement
Kostiggig

Untitled

Apr 13th, 2022
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.71 KB | None | 0 0
  1. interface Work<T> {
  2.  
  3.     fun execute(scope: CoroutineScope,background: suspend () -> T, ui:(T) -> Unit)
  4.  
  5.     class Base(
  6.         private val dispatcher: Dispatcher
  7.     ) : Work<String> {
  8.  
  9.         override fun execute(scope: CoroutineScope, background: suspend () -> String, ui: (String) -> Unit) {
  10.             dispatcher.doBackground(scope) {
  11.                 val result = background.invoke()
  12.                 dispatcher.doUi(scope) {
  13.                     ui.invoke(result)
  14.                 }
  15.             }
  16.         }
  17.  
  18.     }
  19. }
  20.  
  21. interface Dispatcher {
  22.  
  23.     fun doBackground(scope: CoroutineScope,block: suspend () -> Unit)
  24.  
  25.     fun doUi(scope: CoroutineScope,block: suspend () -> Unit)
  26.  
  27.     class Base(
  28.         private val dispatcher: CoroutineDispatcher = Dispatchers.IO
  29.     ) : Dispatcher {
  30.  
  31.         override fun doBackground(scope: CoroutineScope, block: suspend () -> Unit) {
  32.             scope.launch(dispatcher) {
  33.                 block.invoke()
  34.             }
  35.         }
  36.  
  37.         override fun doUi(scope: CoroutineScope,block: suspend () -> Unit) {
  38.             scope.launch(Dispatchers.Main) {
  39.                 block.invoke()
  40.             }
  41.         }
  42.     }
  43. }
  44.  
  45. interface WorkInteractor {
  46.  
  47.     fun string() : String
  48. }
  49.  
  50. interface WorkViewModel {
  51.  
  52.     fun string()
  53.  
  54.     class Base(
  55.         private val workInteractor: WorkInteractor,
  56.         private val work: Work<String>,
  57.         private val communication: Communication<String>
  58.     ) : WorkViewModel, ViewModel() {
  59.  
  60.         override fun string() {
  61.             work.execute(viewModelScope,{
  62.                 workInteractor.string()
  63.             }, { string ->
  64.                 communication.postValue(string)
  65.             })
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement