Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mattiaferigutti/a8a4f35bc8e352d218ed968c3ccbad1d to your computer and use it in GitHub Desktop.
Save mattiaferigutti/a8a4f35bc8e352d218ed968c3ccbad1d to your computer and use it in GitHub Desktop.
// 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