Skip to content

Instantly share code, notes, and snippets.

@bopbi
Created August 11, 2023 14:33
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 bopbi/e5be4667fab19bd0e16a9679ed97db97 to your computer and use it in GitHub Desktop.
Save bopbi/e5be4667fab19bd0e16a9679ed97db97 to your computer and use it in GitHub Desktop.
Use Case DSL
fun main() {
val result = GetLatestStringImpl().invoke()
println(result.getOrNull())
}
interface GetLatestString {
operator fun invoke(): Result<String>
}
class GetLatestStringImpl : GetLatestString {
override operator fun invoke() = getLatestCache(
cacheFound = {
// for logging purpose
},
cacheNotFound = {
fetchFromInternet { result ->
storeToCache(result) {
loadFromCache()
}
}
}
)
private fun loadFromCache(): Result<String> {
return runCatching {
// "value" // result
throw Throwable("not found")
}
}
private fun storeToCache(result: String, function: () -> Result<String>): Result<String> {
// store cache logic there
println("$result inserted to cache")
return function()
}
private fun fetchFromInternet(success:(String) -> Result<String>) : Result<String> {
// perform network request
val networkResult = "value"
return success(networkResult)
}
private fun getLatestCache(cacheFound: (String) -> Unit, cacheNotFound: () -> Result<String>): Result<String> {
return loadFromCache().onFailure {
cacheNotFound()
}.onSuccess {
cacheFound(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment