Last active
October 4, 2022 16:43
-
-
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
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> | |
*/ | |
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