Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import kotlinx.coroutines.CoroutineScope
  2. import kotlinx.coroutines.Dispatchers
  3. import kotlinx.coroutines.launch
  4. import kotlinx.coroutines.withContext
  5.  
  6. class ResultAsync<T> private constructor( scope: CoroutineScope, action: suspend () -> T){
  7.  
  8. var onSuccess : (T) -> Unit = {}
  9. var onError : (e: Throwable) -> Unit = {}
  10. var onStatusChange : (status: AsyncStatus) -> Unit = {}
  11.  
  12. companion object {
  13. fun <T> with( scope: CoroutineScope, action: suspend () -> T) : ResultAsync<T> {
  14. return ResultAsync(scope, action)
  15. }
  16. }
  17.  
  18. init {
  19. scope.launch {
  20. withContext(Dispatchers.Main) { onStatusChange(AsyncStatus.RUNNING) }
  21. try {
  22. val result = action()
  23. withContext(Dispatchers.Main){
  24. onStatusChange(AsyncStatus.DONE)
  25. onSuccess(result)
  26. }
  27. }catch (e:Throwable){
  28. withContext(Dispatchers.Main){
  29. onStatusChange(AsyncStatus.ERROR)
  30. onError(e)
  31. }
  32. }
  33. }
  34. }
  35. }
  36.  
  37. fun <T> ResultAsync<T>.onFailure(action: (exception: Throwable) -> Unit): ResultAsync<T> {
  38. this.onError = action
  39. return this
  40. }
  41.  
  42. fun <T> ResultAsync<T>.onSuccess(action: (value: T) -> Unit): ResultAsync<T> {
  43. this.onSuccess = action
  44. return this
  45. }
  46.  
  47. fun <T> ResultAsync<T>.onStatusChange(action: (AsyncStatus) -> Unit): ResultAsync<T> {
  48. this.onStatusChange = action
  49. return this
  50. }
  51.  
  52. fun <T> CoroutineScope.asyncCatching( action: suspend () -> T): ResultAsync<T> {
  53. return ResultAsync.with( this,action)
  54. }
  55.  
  56.  
  57. enum class AsyncStatus{
  58. RUNNING,
  59. DONE,
  60. ERROR
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement