Skip to content

Instantly share code, notes, and snippets.

@psteiger
Created May 23, 2020 20:05
Show Gist options
  • Select an option

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

Select an option

Save psteiger/17279c8a71215c4d7e475aca5ffbc454 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 Resource<T>.extractData: T? get() = when (this) {
is Success -> data
is Loading -> partialData
is Failure -> null
}
inline fun <Y> Resource<T>.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 Resource<T>.onSuccess(onSuccess: (data: T) -> Unit): Resource<T> {
if (this is Success)
onSuccess(data)
return this
}
fun Resource<T>.onLoading(onLoading: (partialData: T?) -> Unit): Resource<T> {
if (this is Loading)
onLoading(partialData)
return this
}
fun Resource<T>.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