From ee5bf647c6ddccffafe9f1ba1cbbab0a3cf7968f Mon Sep 17 00:00:00 2001 From: Nishant Mishra Date: Wed, 5 Nov 2025 08:51:58 +0530 Subject: [PATCH] fix(timer): significantly reduce recomposition count (by ~90%) This improves the performance and perceived smoothness of the timer screen by a lot --- app/src/main/java/org/nsh07/pomodoro/ui/AppScreen.kt | 5 +---- .../pomodoro/ui/timerScreen/viewModel/TimerViewModel.kt | 9 +++++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/org/nsh07/pomodoro/ui/AppScreen.kt b/app/src/main/java/org/nsh07/pomodoro/ui/AppScreen.kt index 16a539b..e581922 100644 --- a/app/src/main/java/org/nsh07/pomodoro/ui/AppScreen.kt +++ b/app/src/main/java/org/nsh07/pomodoro/ui/AppScreen.kt @@ -45,7 +45,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -79,9 +78,7 @@ fun AppScreen( val context = LocalContext.current val uiState by timerViewModel.timerState.collectAsStateWithLifecycle() - val remainingTime by timerViewModel.time.collectAsStateWithLifecycle() - - val progress by rememberUpdatedState((uiState.totalTime.toFloat() - remainingTime) / uiState.totalTime) + val progress by timerViewModel.progress.collectAsStateWithLifecycle() val layoutDirection = LocalLayoutDirection.current val motionScheme = motionScheme diff --git a/app/src/main/java/org/nsh07/pomodoro/ui/timerScreen/viewModel/TimerViewModel.kt b/app/src/main/java/org/nsh07/pomodoro/ui/timerScreen/viewModel/TimerViewModel.kt index 2c4e493..64fce02 100644 --- a/app/src/main/java/org/nsh07/pomodoro/ui/timerScreen/viewModel/TimerViewModel.kt +++ b/app/src/main/java/org/nsh07/pomodoro/ui/timerScreen/viewModel/TimerViewModel.kt @@ -30,8 +30,11 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.nsh07.pomodoro.TomatoApplication @@ -55,6 +58,12 @@ class TimerViewModel( val timerState: StateFlow = _timerState.asStateFlow() val time: StateFlow = _time.asStateFlow() + + val progress = _time.map { + val uiState = timerState.value + (uiState.totalTime.toFloat() - it) / uiState.totalTime + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0f) + private var cycles = 0 private var startTime = 0L