Add lastUpdate timer feature to adventure to avoid constant refreshing.

This commit is contained in:
Andres Gomez, Thomas (ITDV RL) 2024-06-24 13:43:04 +02:00
parent 2b03ffd1ac
commit 395f54d086
3 changed files with 25 additions and 16 deletions

View file

@ -10,6 +10,7 @@ import com.pixelized.rplexicon.data.parser.adventure.AdventureStoryLineParser
import com.pixelized.rplexicon.data.parser.adventure.AdventureStoryParser
import com.pixelized.rplexicon.data.repository.Adventures
import com.pixelized.rplexicon.data.repository.GoogleSheetServiceRepository
import com.pixelized.rplexicon.utilitary.Update
import com.pixelized.rplexicon.utilitary.exceptions.IncompatibleSheetStructure
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@ -37,6 +38,9 @@ class AdventureRepository @Inject constructor(
private val database = companionDatabase.adventureDao()
private val service = Service()
var lastSuccessFullUpdate: Update = Update.INITIAL
private set
private val adventures = database.let { database ->
combine(
database.getBooksFlow(),
@ -86,6 +90,8 @@ class AdventureRepository @Inject constructor(
(storiesToInsert + storiesToUpdate).forEach { story ->
fetchAndCompareLines(documentId = story.documentId, storyTitle = story.title)
}
lastSuccessFullUpdate = Update.currentTime()
}
@Throws(IncompatibleSheetStructure::class, Exception::class)

View file

@ -52,7 +52,7 @@ fun AdventureBooksScreen(
val screen = LocalScreenNavHost.current
val refresh = rememberPullRefreshState(
refreshing = false,
onRefresh = { viewModel.update() },
onRefresh = { viewModel.update(force = true) },
)
Surface(

View file

@ -52,24 +52,27 @@ class AdventureBooksViewModel @Inject constructor(
init {
viewModelScope.launch(Dispatchers.Default) {
update()
update(force = false)
}
}
fun update() {
viewModelScope.launch {
try {
withContext(Dispatchers.Main) {
_isLoading.value = true
}
withContext(Dispatchers.Default) {
adventureRepository.fetchBooks()
}
} catch (_: Exception) {
_error.emit(value = Structure(ADVENTURE))
} finally {
withContext(Dispatchers.Main) {
_isLoading.value = false
fun update(force: Boolean = false) {
if (force || adventureRepository.lastSuccessFullUpdate.shouldUpdate()) {
viewModelScope.launch {
try {
withContext(Dispatchers.Main) {
_isLoading.value = true
}
withContext(Dispatchers.Default) {
adventureRepository.fetchBooks()
}
} catch (_: Exception) {
_error.emit(value = Structure(ADVENTURE))
} finally {
withContext(Dispatchers.Main) {
_isLoading.value = false
}
}
}
}