Skip to content

Instantly share code, notes, and snippets.

@LukaKordic
Created September 4, 2019 09:00
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/a53438a5b5c04b2ec17f43887d19f737 to your computer and use it in GitHub Desktop.
Save LukaKordic/a53438a5b5c04b2ec17f43887d19f737 to your computer and use it in GitHub Desktop.
abstract class BaseRepository<T : Any, R : DomainMapper<T>> : KoinComponent {
private val connectivity: Connectivity by inject()
private val contextProvider: CoroutineContextProvider by inject()
/**
* Use this if you need to cache data after fetching it from the api, or retrieve something from cache
*/
protected suspend fun fetchData(
apiDataProvider: suspend () -> Result<T>,
dbDataProvider: suspend () -> R
): Result<T> {
return if (connectivity.hasNetworkAccess()) {
withContext(contextProvider.io) {
apiDataProvider()
}
} else {
withContext(contextProvider.io) {
val dbResult = dbDataProvider()
if (dbResult != null) Success(dbResult.mapToDomainModel()) else Failure(HttpError(Throwable(DB_ENTRY_ERROR)))
}
}
}
/**
* Use this when communicating only with the api service
*/
protected suspend fun fetchData(dataProvider: () -> Result<T>): Result<T> {
return if (connectivity.hasNetworkAccess()) {
withContext(contextProvider.io) {
dataProvider()
}
} else {
Failure(HttpError(Throwable(GENERAL_NETWORK_ERROR)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment