Last active
September 4, 2019 09:05
-
-
Save LukaKordic/a8345d3804619351b21a0607469f7fb7 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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