Skip to content

Instantly share code, notes, and snippets.

@psteiger
Last active May 19, 2020 14:09
Show Gist options
  • Select an option

  • Save psteiger/d5df0a73f03354379f35cf50dc08699b to your computer and use it in GitHub Desktop.

Select an option

Save psteiger/d5df0a73f03354379f35cf50dc08699b to your computer and use it in GitHub Desktop.
sealed class Resource<out T> {
data class Success<out T>(val data: T) : Resource<T>()
data class Loading<out T>(val partialData: T? = null) : Resource<T>()
data class Failure<out T>(val throwable: Throwable? = null) : Resource<T>()
val extractData: T? get() = when (this) {
is Success -> data
is Loading -> partialData
is Failure -> null
}
inline fun <Y> mapResource(crossinline transform: (T) -> Y): Resource<Y> = try {
when (this) {
is Success<T> -> Success<Y>(transform(data))
is Loading<T> -> Loading<Y>(partialData?.let { transform(it) })
is Failure<T> -> Failure<Y>(throwable)
}
} catch (e: Throwable) {
Resource.Failure<Y>(e)
}
fun onSuccess(onSuccess: (data: T) -> Unit): Resource<T> {
if (this is Success)
onSuccess(data)
return this
}
fun onLoading(onLoading: (partialData: T?) -> Unit): Resource<T> {
if (this is Loading)
onLoading(partialData)
return this
}
fun onFailure(onFailure: (throwable: Throwable?) -> Unit): Resource<T> {
if (this is Failure)
onFailure(throwable)
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment