Last active
November 28, 2018 13:49
-
-
Save diefferson/bef16c5ee0f3bee6d78eb85d799f0325 to your computer and use it in GitHub Desktop.
Result Patern to Coroutines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.launch | |
class ResultAsync<T> private constructor(action: suspend () -> T, scope: CoroutineScope) { | |
internal var onSuccess : (T) -> Unit = {} | |
internal var onError : (e: Throwable) -> Unit = {} | |
companion object { | |
fun <T> with(action: suspend () -> T, scope: CoroutineScope) :ResultAsync<T>{ | |
return ResultAsync(action, scope) | |
} | |
} | |
init { | |
scope.launch { | |
try { | |
val result = action() | |
onSuccess(result) | |
}catch (e:Throwable){ | |
onError(e) | |
} | |
} | |
} | |
} | |
fun <T> ResultAsync<T>.onFailure(action: (exception: Throwable) -> Unit): ResultAsync<T> { | |
this.onError = action | |
return this | |
} | |
fun <T> ResultAsync<T>.onSuccess(action: (value: T) -> Unit): ResultAsync<T> { | |
this.onSuccess = action | |
return this | |
} | |
fun <T> CoroutineScope.asyncCatching(action: suspend () -> T):ResultAsync<T>{ | |
return ResultAsync.with(action, this) | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//In your class that extends CoroutineScope | |
fun getUser(){ | |
asyncCatching{ | |
userRepository.getUser() | |
}.onFailure { | |
Log.i("ERRO", it.message) | |
}.onSuccess { | |
user = it | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment