Skip to content

Instantly share code, notes, and snippets.

@alashow
Last active June 4, 2021 22:39
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 alashow/4a4ce4283c1467e8ed3b79d7139fc451 to your computer and use it in GitHub Desktop.
Save alashow/4a4ce4283c1467e8ed3b79d7139fc451 to your computer and use it in GitHub Desktop.
/**
* The T generic is unused for some classes but since it is sealed and useful for Success and Fail,
* it should be on all of them.
*
* Complete: Success, Fail
* ShouldLoad: Uninitialized, Fail
*/
sealed class Async<out T>(val complete: Boolean, val shouldLoad: Boolean) {
open operator fun invoke(): T? = null
fun success(block: (T) -> Unit) = if (this is Success) {
block(this())
} else pass
}
object Uninitialized : Async<Nothing>(complete = false, shouldLoad = true), Incomplete
class Loading<out T> : Async<T>(complete = false, shouldLoad = false), Incomplete {
override fun equals(other: Any?) = other is Loading<*>
override fun hashCode() = "Loading".hashCode()
}
data class Success<out T>(private val value: T) : Async<T>(complete = true, shouldLoad = false) {
override operator fun invoke(): T = value
}
data class Fail<out T>(val error: Throwable) : Async<T>(complete = true, shouldLoad = true)
interface Incomplete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment