Skip to content

Instantly share code, notes, and snippets.

@granoeste
Created January 13, 2022 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save granoeste/1e6938a6247f5248b121e1191ae7119d to your computer and use it in GitHub Desktop.
Save granoeste/1e6938a6247f5248b121e1191ae7119d to your computer and use it in GitHub Desktop.
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