From 07808be975fc4edc58bd1e608339bea3c7742f0b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Jan 2026 21:14:43 +0000 Subject: [PATCH] Fix sun data refresh on app resume and periodic refresh The periodic refresh was broken because collectLatest on a Room Flow suspends indefinitely, preventing the while loop from advancing. Replace with Flow.first() for one-shot snapshots. Add refresh() method triggered via LifecycleEventEffect(ON_RESUME) so sun times recalculate every time the app comes to foreground. https://claude.ai/code/session_01QD2KVpt2xSRtRALne48g3n --- .../main/java/com/sunzones/ui/main/MainScreen.kt | 6 ++++++ .../java/com/sunzones/ui/main/MainViewModel.kt | 16 +++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/sunzones/ui/main/MainScreen.kt b/app/src/main/java/com/sunzones/ui/main/MainScreen.kt index a380358..5a6a965 100644 --- a/app/src/main/java/com/sunzones/ui/main/MainScreen.kt +++ b/app/src/main/java/com/sunzones/ui/main/MainScreen.kt @@ -20,6 +20,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush @@ -43,6 +45,10 @@ fun MainScreen( val uiState by viewModel.uiState.collectAsState() var showAddSheet by remember { mutableStateOf(false) } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + viewModel.refresh() + } + Box(modifier = Modifier.fillMaxSize()) { if (uiState.locations.isEmpty() && !uiState.isLoading) { // Empty state diff --git a/app/src/main/java/com/sunzones/ui/main/MainViewModel.kt b/app/src/main/java/com/sunzones/ui/main/MainViewModel.kt index 5bb4c61..37c4674 100644 --- a/app/src/main/java/com/sunzones/ui/main/MainViewModel.kt +++ b/app/src/main/java/com/sunzones/ui/main/MainViewModel.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.first import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -75,13 +76,22 @@ class MainViewModel @Inject constructor( viewModelScope.launch { while (isActive) { delay(60_000L) // refresh every minute for sun progress updates - getLocationsUseCase().collectLatest { locations -> - _uiState.value = _uiState.value.copy(locations = locations) - } + refreshNow() } } } + fun refresh() { + viewModelScope.launch { + refreshNow() + } + } + + private suspend fun refreshNow() { + val locations = getLocationsUseCase().first() + _uiState.value = _uiState.value.copy(locations = locations) + } + fun deleteLocation(id: Long) { viewModelScope.launch { repository.deleteLocation(id)