Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A generic class that holds a value with its loading status.
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
// ImmutableClass
class Resource<T> private constructor(
val status: Status,
val data: T? = null,
val throwable: Throwable? = null,
val id: Long = 0
) {
companion object {
fun <T> success(data: T): Resource<T> = Resource(Status.SUCCESS, data = data)
fun <T> error(throwable: Throwable): Resource<T> = Resource(Status.ERROR, throwable = throwable)
fun <T> loading(): Resource<T> = Resource(Status.LOADING)
fun <T> loading(id: Long): Resource<T> = Resource(Status.LOADING, id = id)
}
var hasBeenHandled = false
private set // Allow external read but not write
fun getContentIfNotHandled(): Resource<T>? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
this
}
}
fun peekContent(): Resource<T> = this
override fun toString(): String {
return "Resource(status=$status, data=$data, throwable=$throwable, hasBeenHandled=$hasBeenHandled)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment