Created
August 11, 2023 14:33
-
-
Save bopbi/e5be4667fab19bd0e16a9679ed97db97 to your computer and use it in GitHub Desktop.
Use Case DSL
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() { | |
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