Skip to content

Instantly share code, notes, and snippets.

@diefferson
Last active November 28, 2018 13:49
Show Gist options
  • Save diefferson/bef16c5ee0f3bee6d78eb85d799f0325 to your computer and use it in GitHub Desktop.
Save diefferson/bef16c5ee0f3bee6d78eb85d799f0325 to your computer and use it in GitHub Desktop.
Result Patern to Coroutines
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)
}
//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