Created
January 13, 2022 02:25
-
-
Save granoeste/1e6938a6247f5248b121e1191ae7119d to your computer and use it in GitHub Desktop.
A generic class that holds a value with its loading status.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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