Last active
June 4, 2022 15:02
-
-
Save mattiaferigutti/a8a4f35bc8e352d218ed968c3ccbad1d 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
// 1 | |
sealed class ResultOf<out T> { | |
data class Success<out R>(val value: R): ResultOf<R>() | |
data class Failure( | |
val message: String? = null, | |
val throwable: Throwable? = null | |
): ResultOf<Nothing>() | |
} | |
inline fun <reified T> ResultOf<T>.doIfFailureWithResult(callback: (error: String?, throwable: Throwable?) -> Unit) : Boolean? { | |
if (this is ResultOf.Failure) { | |
callback(message, throwable) | |
return false | |
} | |
return null | |
} | |
inline fun <reified T> ResultOf<T>.doIfSuccessWithResult(callback: (value: T) -> Unit) : Boolean? { | |
if (this is ResultOf.Success) { | |
callback(value) | |
return true | |
} | |
return null | |
} | |
// 2 | |
val result = async { | |
withContext(Dispatchers.Default) { | |
with(fetchData()) { | |
doIfSuccessWithResult { variant -> | |
// do stuff | |
return@withContext true | |
} | |
doIfFailureWithResult { error, throwable -> | |
// do stuff | |
return@withContext false | |
} | |
} | |
} | |
} | |
return@withContext result.await() ?: false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment