Last active
August 6, 2024 00:02
-
-
Save BolajiOlajide/d04a31170aeb29a7ba6f06d67faa3b57 to your computer and use it in GitHub Desktop.
Enums and State in Kotlin
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
| 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