From 7c4f1c7b22a8a67df9c5575ab74b7651555e4b59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Pich?= Date: Tue, 12 Jul 2022 12:23:55 +0200 Subject: [PATCH] Add auto refresh to reporting units (#1916) --- .../repositories/ReportingUnitRepository.kt | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/ReportingUnitRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/ReportingUnitRepository.kt index b9caf978b..84055cef0 100644 --- a/app/src/main/java/io/github/wulkanowy/data/repositories/ReportingUnitRepository.kt +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/ReportingUnitRepository.kt @@ -5,6 +5,8 @@ import io.github.wulkanowy.data.db.entities.ReportingUnit import io.github.wulkanowy.data.db.entities.Student import io.github.wulkanowy.data.mappers.mapToEntities import io.github.wulkanowy.sdk.Sdk +import io.github.wulkanowy.utils.AutoRefreshHelper +import io.github.wulkanowy.utils.getRefreshKey import io.github.wulkanowy.utils.init import io.github.wulkanowy.utils.uniqueSubtract import javax.inject.Inject @@ -13,30 +15,39 @@ import javax.inject.Singleton @Singleton class ReportingUnitRepository @Inject constructor( private val reportingUnitDb: ReportingUnitDao, - private val sdk: Sdk + private val sdk: Sdk, + private val refreshHelper: AutoRefreshHelper, ) { + private val cacheKey = "reporting_unit" + suspend fun refreshReportingUnits(student: Student) { val new = sdk.init(student).getReportingUnits().mapToEntities(student) val old = reportingUnitDb.load(student.id.toInt()) reportingUnitDb.deleteAll(old.uniqueSubtract(new)) reportingUnitDb.insertAll(new.uniqueSubtract(old)) + + refreshHelper.updateLastRefreshTimestamp(getRefreshKey(cacheKey, student)) } suspend fun getReportingUnits(student: Student): List { - return reportingUnitDb.load(student.id.toInt()).ifEmpty { - refreshReportingUnits(student) + val cached = reportingUnitDb.load(student.id.toInt()) + val isExpired = refreshHelper.shouldBeRefreshed(getRefreshKey(cacheKey, student)) + return if (cached.isEmpty() || isExpired) { + refreshReportingUnits(student) reportingUnitDb.load(student.id.toInt()) - } + } else cached } suspend fun getReportingUnit(student: Student, unitId: Int): ReportingUnit? { - return reportingUnitDb.loadOne(student.id.toInt(), unitId) ?: run { - refreshReportingUnits(student) + val cached = reportingUnitDb.loadOne(student.id.toInt(), unitId) + val isExpired = refreshHelper.shouldBeRefreshed(getRefreshKey(cacheKey, student)) - return reportingUnitDb.loadOne(student.id.toInt(), unitId) - } + return if (cached == null || isExpired) { + refreshReportingUnits(student) + reportingUnitDb.loadOne(student.id.toInt(), unitId) + } else cached } }