Skip to content

Instantly share code, notes, and snippets.

@gsusmonzon
Last active October 4, 2022 16:43
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 gsusmonzon/02d121cad13dd42c35524580679c6f6d to your computer and use it in GitHub Desktop.
Save gsusmonzon/02d121cad13dd42c35524580679c6f6d to your computer and use it in GitHub Desktop.
A generic class that holds a value with its loading status. Like a Result, but with a `Loading` state
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
sealed class ResourceState<out T> {
open val isSuccess get():Boolean {return false}
open val isFailure get():Boolean {return false}
open val isLoading get():Boolean {return false}
open fun getOrNull(): T? {return null}
open fun exceptionOrNull(): Throwable? {return null}
data class Success<out T>(val data: T) : ResourceState<T>(){
override val isSuccess get():Boolean = true
override fun getOrNull(): T? = data
}
data class Error(val exception: Throwable? = null) : ResourceState<Nothing>(){
override val isFailure get(): Boolean = true
override fun exceptionOrNull(): Throwable? = exception
}
data class Loading(val loading: Boolean = true) : ResourceState<Nothing>() {
override val isLoading get():Boolean = loading
}
override fun toString(): String {
return when (this) {
is Success<T> -> "Success[data=$data]"
is Loading -> "Loading[loading=$loading]"
is Error -> "Error[exception=$exception]"
}
}
fun <O>convertType(srcObject: O) : ResourceState<O> =
if (this.isSuccess) {
Success(srcObject)
} else if (this.isFailure) {
Error(this.exceptionOrNull())
} else {
Loading(this.isLoading)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment