Modern Apps git

← Modern-Apps.git

weather: widgets fall back to a pinned location when GPS cache is missing

Commit
d5aad72cc0dd29d1d1f71dc0f1060f2de6afed81
Author
Vayun Mathur <[email protected]>
When
2026-11-30 19:39 UTC (5 days ago)
Parents
3cf1174
Both Glance widgets rendered 'no data' whenever a device-location
row existed but its forecast cache was missing, corrupt or lacked
a current block — even with a perfectly valid pinned location
cached. That state is routine: the device row is created before
its first fetch lands, a >500 m move orphans the old coordinates'
cache, and offline fetch failures leave the new row uncached.
loadWeatherSnapshot implemented only half of its own contract:
the pinned fallback ran only when no device row existed at all.

The snapshot loader now walks an ordered candidate list (device
row first, then saved locations in display order, deduped) and
returns the first cache that yields a snapshot. Still cache-only —
no network on the widget path — and the device location still wins
when its cache is usable. Three regression tests cover miss,
corrupt cache, and device-wins. Verified: :weather:testDevUnitTest
236 tests pass; lint errors are pre-existing on untouched Route.kt.

Diff

weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.ktindex c2327b89fb..ecb8083b34 100644--- a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt@@ -2,6 +2,7 @@ package com.vayunmathur.weather.widget import com.vayunmathur.weather.network.ForecastResponse import com.vayunmathur.weather.domain.roundCoord import com.vayunmathur.weather.data.weatherJson+import com.vayunmathur.weather.data.SavedLocation import com.vayunmathur.weather.data.WeatherRepository import com.vayunmathur.library.log.Log import com.vayunmathur.weather.data.WeatherRefreshWorker@@ -254,9 +255,12 @@ class WeatherGlanceWidgetReceiver : MaWidgetReceiver<WeatherGlanceWidget>( /**  * Snapshot of cached weather used by the widgets. Populated from the  * most-recent [com.vayunmathur.weather.data.WeatherCache] row for the- * user's primary saved location (preferring the device-location row).- * `null` while no forecast has been cached yet — the widget renders a- * dash in that case rather than failing to load.+ * user's primary saved location (preferring the device-location row,+ * then the saved locations in display order). A location whose cache is+ * missing or unusable is skipped, so one uncached location never blanks+ * the widget while another location's forecast is cached. `null` only+ * while no location has a usable cached forecast yet — the widget+ * renders a dash in that case rather than failing to load.  */ data class WidgetWeather(     val temperatureCelsius: Double,@@ -270,25 +274,35 @@ data class WidgetWeather( internal suspend fun loadWeatherSnapshot(context: Context): WidgetWeather? {     return try {         val repo = WeatherRepository.get(context)-        // Prefer the device-current row, fall back to the first pinned location.-        val location = repo.getCurrentDeviceLocation()-            ?: repo.getLocations().firstOrNull()-            ?: return null-        val cache = repo.getCache(-            roundCoord(location.latitude),-            roundCoord(location.longitude),-        ) ?: return null-        val forecast = runCatching {-            weatherJson.decodeFromString<ForecastResponse>(cache.forecastJson)-        }.getOrNull() ?: return null-        val current = forecast.current ?: return null-        WidgetWeather(-            temperatureCelsius = current.temperature,-            weatherCode = current.weatherCode,-            isDay = current.isDay != 0,-        )+        // Prefer the device-current row, then the saved locations in+        // display order; skip any whose cache cannot produce a snapshot.+        val candidates = buildList {+            repo.getCurrentDeviceLocation()?.let { add(it) }+            addAll(repo.getLocations())+        }.distinctBy { it.id }+        candidates.firstNotNullOfOrNull { snapshotFor(repo, it) }     } catch (e: Exception) {         Log.dev("WeatherWidget", "no cached snapshot yet", e)         null     } }++/** The snapshot for one [location]'s cache row, or null when unusable. */+private suspend fun snapshotFor(+    repo: WeatherRepository,+    location: SavedLocation,+): WidgetWeather? {+    val cache = repo.getCache(+        roundCoord(location.latitude),+        roundCoord(location.longitude),+    ) ?: return null+    val forecast = runCatching {+        weatherJson.decodeFromString<ForecastResponse>(cache.forecastJson)+    }.getOrNull() ?: return null+    val current = forecast.current ?: return null+    return WidgetWeather(+        temperatureCelsius = current.temperature,+        weatherCode = current.weatherCode,+        isDay = current.isDay != 0,+    )+}
weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt b/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.ktindex 0246366412..96257520ac 100644--- a/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/data/WeatherWorkerAndWidgetTest.kt@@ -103,6 +103,47 @@ class WeatherWorkerAndWidgetTest {         assertEquals(false, snapshot.isDay)     } +    private fun forecastAt(temp: Double, code: Int = 1, isDay: Int = 1) = ForecastResponse(+        latitude = 0.0, longitude = 0.0,+        current = com.vayunmathur.weather.network.Current(+            time = "2026-07-15T14:30", temperature = temp, apparentTemperature = temp,+            relativeHumidity = 50, windSpeed = 5.0, windDirection = 90,+            weatherCode = code, isDay = isDay,+        ),+    )++    @Test fun widgetSnapshotFallsBackToPinnedWhenDeviceCacheMissing() = runTest {+        // Device row exists (e.g. just created, or moved before its first+        // fetch landed) but has no cache; the pinned location does.+        repo.insertLocation(loc("GPS", current = true, lat = 52.5, lon = 13.4))+        repo.insertLocation(loc("Paris", lat = 48.85, lon = 2.35))+        repo.writeForecastCache(48.85, 2.35, forecastAt(18.0, code = 2), fetchedAtEpochMs = 3000L)+        val snapshot = assertNotNull(loadWeatherSnapshot(ctx))+        assertEquals(18.0, snapshot.temperatureCelsius)+        assertEquals(2, snapshot.weatherCode)+    }++    @Test fun widgetSnapshotFallsBackToPinnedWhenDeviceCacheCorrupt() = runTest {+        repo.insertLocation(loc("GPS", current = true, lat = 52.5, lon = 13.4))+        repo.insertLocation(loc("Paris", lat = 48.85, lon = 2.35))+        repo.upsertCache(+            WeatherCache(+                latRounded = roundCoord(52.5), lonRounded = roundCoord(13.4),+                forecastJson = "{broken", fetchedAtEpochMs = 1L,+            )+        )+        repo.writeForecastCache(48.85, 2.35, forecastAt(19.5), fetchedAtEpochMs = 3000L)+        assertEquals(19.5, assertNotNull(loadWeatherSnapshot(ctx)).temperatureCelsius)+    }++    @Test fun widgetSnapshotPrefersDeviceCacheOverPinned() = runTest {+        repo.insertLocation(loc("GPS", current = true, lat = 52.5, lon = 13.4))+        repo.insertLocation(loc("Paris", lat = 48.85, lon = 2.35))+        repo.writeForecastCache(48.85, 2.35, forecastAt(18.0), fetchedAtEpochMs = 3000L)+        repo.writeForecastCache(52.5, 13.4, forecastAt(24.0), fetchedAtEpochMs = 4000L)+        assertEquals(24.0, assertNotNull(loadWeatherSnapshot(ctx)).temperatureCelsius)+    }+     @Test fun widgetSnapshotFallsBackToFirstPinnedAndHandlesMisses() = runTest {         // No locations at all -> no snapshot.         assertNull(loadWeatherSnapshot(ctx))