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)