I'm currently using the algorithm networkboundresource provided by google, it has it's limitations and I wanted to know what is the best way to go about it?
I want to fetch data, cache it and to update the cached data whenever new data has been added to the server/remote database
override suspend fun getSelectRoute(
id: String,
date: String,
date2: String
): Flow<Resource<List<SelectRoute>>> {
return networkBoundResource(
query = {
selectRouteEntityMapper.mapToDomainModelFlowList(selectRouteDao.getSelectRoute())
},
fetch = {
selectRouteDtoMapper.mapToDomainModelList(
selectRouteService.getSelectRoute(
id = id,
date = date,
date2 = date2
)
)
},
saveFetchResult = {
actraDB.withTransaction {
selectRouteDao.deleteAllSelectRoute()
completedRoutesDao.deleteCompletedRoutes()
it.forEach {
selectRouteDao.insertSelectRoute(
selectRouteEntityMapper.mapFromDomainModel(it)
)
completedRoutesDao.insertCompletedRoute(
completedRoutesEntityMapper.mapFromDomainModel(it)
)
Log.d("repolist", "${it.address1}")
}
}
}
)
inline fun <ResultType, RequestType> networkBoundResource(
crossinline query: () -> Flow<ResultType>,
crossinline fetch: suspend () -> RequestType,
crossinline saveFetchResult: suspend (RequestType) -> Unit,
crossinline shouldFetch: (ResultType) -> Boolean = { true }
) = flow {
val data = query().first()
val flow = if (shouldFetch(data)) {
emit(Resource.Loading(data))
try {
saveFetchResult(fetch())
query().map { Resource.Success(it) }
} catch (throwable: Throwable) {
query().map { Resource.Error(throwable.message, it) }
}
}else{
query().map { Resource.Success(it) }
}
emitAll(flow = flow)
}