Skip to content

Instantly share code, notes, and snippets.

@LukaKordic
Last active September 4, 2019 09:05
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 LukaKordic/a8345d3804619351b21a0607469f7fb7 to your computer and use it in GitHub Desktop.
Save LukaKordic/a8345d3804619351b21a0607469f7fb7 to your computer and use it in GitHub Desktop.
/**
* Use this if you need to cache data after fetching it from the api, or retrieve something from cache
*/
inline fun <T : RoomMapper<R>, R : DomainMapper<U>, U : Any> Response<T>.getData(
cacheAction: (R) -> Unit,
fetchFromCacheAction: () -> R): Result<U> {
try {
onSuccess {
val databaseEntity = it.mapToRoomEntity()
cacheAction(databaseEntity)
return Success(databaseEntity.mapToDomainModel())
}
onFailure {
val cachedModel = fetchFromCacheAction()
if (cachedModel != null) Success(cachedModel.mapToDomainModel()) else Failure(HttpError(Throwable(DB_ENTRY_ERROR)))
}
return Failure(HttpError(Throwable(GENERAL_NETWORK_ERROR)))
} catch (e: IOException) {
return Failure(HttpError(Throwable(GENERAL_NETWORK_ERROR)))
}
}
/**
* Use this when communicating only with the api service
*/
fun <T : DomainMapper<R>, R : Any> Response<T>.getData(): Result<R> {
try {
onSuccess { return Success(it.mapToDomainModel()) }
onFailure { return Failure(it) }
return Failure(HttpError(Throwable(GENERAL_NETWORK_ERROR)))
} catch (e: IOException) {
return Failure(HttpError(Throwable(GENERAL_NETWORK_ERROR)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment