Created
October 18, 2020 14:56
-
-
Save oscarcidcoder/ce3410324bf4b63fb568fe64e4ee1b7c to your computer and use it in GitHub Desktop.
This file contains 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
// https://medium.com/swlh/kotlin-sealed-class-for-success-and-error-handling-d3054bef0d4e | |
// https://medium.com/androiddevelopers/sealed-with-a-class-a906f28ab7b5 | |
sealed class ResultOf<out T: Any> { | |
data class Success<out T: Any>(val value: T): ResultOf<T>() | |
data class Error( | |
val message: String?, | |
val throwable: Throwable? | |
): ResultOf<Nothing>() | |
object InProgress : ResultOf<Nothing>() | |
companion object Factory{ | |
inline fun <T> build(function: () -> T): ResultOf<T> = | |
try { | |
Success(function.invoke()) | |
} catch (e: java.lang.Exception) { | |
Error(e.getMessage(),e) | |
} | |
} | |
/* ej. | |
Result.build { | |
task.toObject(FirebaseNote::class.java)?.toNote ?: throw Exception() | |
} | |
*/ | |
} | |
// Extensions | |
inline fun <reified T> ResultOf<T>.doIfFailure(callback: (error: String?, throwable: Throwable?) -> Unit) { | |
if (this is ResultOf.Failure) { | |
callback(message, throwable) | |
} | |
} | |
inline fun <reified T> ResultOf<T>.doIfSuccess(callback: (value: T) -> Unit) { | |
if (this is ResultOf.Success) { | |
callback(value) | |
} | |
} | |
inline fun <reified T, reified R> ResultOf<T>.map(transform: (T) -> R): ResultOf<R> { | |
return when (this) { | |
is ResultOf.Success -> ResultOf.Success(transform(value)) | |
is ResultOf.Failure -> this | |
} | |
} | |
inline fun <T> ResultOf<T>.withDefault(value: () -> T): ResultOf.Success<T> { | |
return when (this) { | |
is ResultOf.Success -> this | |
is ResultOf.Failure -> ResultOf.Success(value()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment