Last active
August 6, 2024 00:16
-
-
Save BolajiOlajide/43b9f013c95dcc7c7b89b3e85152759b to your computer and use it in GitHub Desktop.
abstract_class.kt
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) { | |
is Error -> { | |
println(result.exception.toString()) | |
} | |
is Success -> { | |
println(result.dataFetched?: "Ensure you start the fetched function first.") | |
} | |
is Pending -> { | |
println("Loading") | |
} | |
is Idle -> { | |
println("Idle") | |
} | |
else -> println("N/A") | |
} | |
} | |
// This is a singleton class, there'll always be | |
// only one instance of this class. | |
object Repository { | |
private var loadState: Result = Idle | |
private var dataFetched: String? = null | |
fun startFetch() { | |
loadState = Pending | |
dataFetched = "Data" | |
} | |
fun finishFetch() { | |
loadState = Success(dataFetched = dataFetched) | |
dataFetched = null | |
} | |
fun error() { | |
loadState = Error(exception = Exception("xecption")) | |
} | |
fun getCurrentState(): Result { | |
return loadState | |
} | |
} | |
abstract class Result | |
data class Success(val dataFetched: String?): Result() | |
data class Error(val exception: Exception): Result() | |
object Pending: Result() | |
object Idle: Result() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment