Created
September 4, 2019 09:00
-
-
Save LukaKordic/a53438a5b5c04b2ec17f43887d19f737 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
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