Skip to content

Instantly share code, notes, and snippets.

@BolajiOlajide
Last active August 6, 2024 00:02
Show Gist options
  • Select an option

  • Save BolajiOlajide/d04a31170aeb29a7ba6f06d67faa3b57 to your computer and use it in GitHub Desktop.

Select an option

Save BolajiOlajide/d04a31170aeb29a7ba6f06d67faa3b57 to your computer and use it in GitHub Desktop.
Enums and State in Kotlin
fun main() {
Repository.startFetch()
getResult(Repository.getCurrentState())
Repository.finishFetch()
getResult(Repository.getCurrentState())
Repository.error()
getResult(Repository.getCurrentState())
}
fun getResult(result: Result) {
return when(result) {
Result.SUCCESS -> println("Success")
Result.FAILURE -> println("Failure")
Result.ERROR -> println("Error!")
Result.IDLE -> println("Idle")
Result.PENDING -> println("Pending")
}
}
// This is a singleton class, there'll always be
// only one instance of this class.
object Repository {
private var loadState: Result = Result.IDLE
private var dataFetched: String? = null
fun startFetch() {
loadState = Result.PENDING
dataFetched = "Data"
}
fun finishFetch() {
loadState = Result.SUCCESS
dataFetched = null
}
fun error() {
loadState = Result.ERROR
}
fun getCurrentState(): Result {
return loadState
}
}
enum class Result {
SUCCESS,
FAILURE,
ERROR,
PENDING,
IDLE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment