Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2026-09-18 - Decoupling High-Frequency Timers in Flow Combine & Compose Stability
**Learning:** Combining a high-frequency ticker flow (like a 1s live duration timer) with list statistics recalculations in `combine` causes O(N) list operations on every tick. Additionally, data classes with `List<T>` properties are inferred as unstable by Compose unless marked `@Immutable`.
**Action:** Extract list transforms into a separate `map` flow before `combine` so operations run only when database emissions occur, and annotate state data classes with `@Immutable`.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.felixbrucker.sleeptracker.ui.viewmodel

import android.app.Application
import androidx.compose.runtime.Immutable
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
Expand All @@ -18,11 +19,13 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds

@Immutable
data class SleepTrackerUiState(
val isTrackingActive: Boolean = false,
val trackingStartTimeMillis: Long = 0L,
Expand All @@ -43,6 +46,13 @@ data class SleepTrackerUiState(
val statusMessage: String? = null
)

private data class SessionStats(
val sessions: List<SleepSessionEntity> = emptyList(),
val totalSessions: Int = 0,
val totalDurationMillis: Long = 0L,
val averageDurationMillis: Long = 0L
)

class SleepViewModel(
application: Application,
private val repository: SleepRepository,
Expand All @@ -57,17 +67,25 @@ class SleepViewModel(
Pair(healthConnectManager.isAvailable, false)
)

private val _sessionStats = repository.allSessions.map { sessions ->
val totalSessions = sessions.size
val totalDuration = sessions.sumOf { it.durationMillis }
val avgDuration = if (totalSessions > 0) totalDuration / totalSessions else 0L
SessionStats(
sessions = sessions,
totalSessions = totalSessions,
totalDurationMillis = totalDuration,
averageDurationMillis = avgDuration
)
}

val uiState: StateFlow<SleepTrackerUiState> = combine(
repository.preferencesFlow,
repository.allSessions,
_sessionStats,
_liveDuration,
_healthConnectStatus,
_statusMessage
) { prefs, sessions, duration, hcStatus, message ->
val totalSessions = sessions.size
val totalDuration = sessions.sumOf { it.durationMillis }
val avgDuration = if (totalSessions > 0) totalDuration / totalSessions else 0L

) { prefs, stats, duration, hcStatus, message ->
val now = System.currentTimeMillis()
val fallAsleepMillis = prefs.fallAsleepDurationMinutes * 60_000L
val sleepStartTime = prefs.trackingStartTimeMillis + fallAsleepMillis
Expand All @@ -92,10 +110,10 @@ class SleepViewModel(
autoSyncHealthConnect = prefs.autoSyncHealthConnect,
healthConnectAvailable = hcStatus.first,
healthConnectPermissionsGranted = hcStatus.second,
sessions = sessions,
totalSleepSessions = totalSessions,
totalSleepDurationMillis = totalDuration,
averageSleepDurationMillis = avgDuration,
sessions = stats.sessions,
totalSleepSessions = stats.totalSessions,
totalSleepDurationMillis = stats.totalDurationMillis,
averageSleepDurationMillis = stats.averageDurationMillis,
statusMessage = message
)
}.stateIn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,33 +26,34 @@ fun Long.toFormattedDuration(): String {
}
}

// Thread-safe cached formatters to prevent repeated allocations in hot rendering paths.
private val timeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault())
private val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE, MMM d", Locale.getDefault())
private val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("MMM d, HH:mm", Locale.getDefault())

fun Long.toFormattedTime(zoneId: ZoneId = ZoneId.systemDefault()): String {
if (this <= 0L) return "--:--"
val instant = Instant.ofEpochMilli(this)
val formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault())
return instant.atZone(zoneId).format(formatter)
return instant.atZone(zoneId).format(timeFormatter)
}

fun Long.toFormattedDate(zoneId: ZoneId = ZoneId.systemDefault()): String {
if (this <= 0L) return ""
val instant = Instant.ofEpochMilli(this)
val formatter = DateTimeFormatter.ofPattern("EEE, MMM d", Locale.getDefault())
return instant.atZone(zoneId).format(formatter)
return instant.atZone(zoneId).format(dateFormatter)
}

fun Long.toFormattedDateTime(zoneId: ZoneId = ZoneId.systemDefault()): String {
if (this <= 0L) return ""
val instant = Instant.ofEpochMilli(this)
val formatter = DateTimeFormatter.ofPattern("MMM d, HH:mm", Locale.getDefault())
return instant.atZone(zoneId).format(formatter)
return instant.atZone(zoneId).format(dateTimeFormatter)
}

fun Int.padTwoDigits(): String = String.format(Locale.getDefault(), "%02d", this)

fun formatTimeDisplay(hour: Int, minute: Int): String {
val formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault())
val localDateTime = LocalDateTime.of(2026, 1, 1, hour, minute)
return localDateTime.format(formatter)
return localDateTime.format(timeFormatter)
}

fun calculateNextAlarmTime(
Expand Down
Empty file modified gradlew
100644 → 100755
Empty file.
Loading