|
17 | 17 | package org.meshtastic.feature.widget |
18 | 18 |
|
19 | 19 | import android.content.Context |
| 20 | +import androidx.glance.appwidget.GlanceAppWidgetManager |
20 | 21 | import androidx.glance.appwidget.updateAll |
21 | 22 | import co.touchlab.kermit.Logger |
| 23 | +import kotlinx.coroutines.CoroutineScope |
| 24 | +import kotlinx.coroutines.Dispatchers |
| 25 | +import kotlinx.coroutines.FlowPreview |
| 26 | +import kotlinx.coroutines.SupervisorJob |
| 27 | +import kotlinx.coroutines.flow.debounce |
| 28 | +import kotlinx.coroutines.flow.distinctUntilChanged |
| 29 | +import kotlinx.coroutines.launch |
22 | 30 | import org.koin.core.annotation.Single |
23 | 31 | import org.meshtastic.core.repository.AppWidgetUpdater |
24 | 32 |
|
| 33 | +private const val WIDGET_UPDATE_DEBOUNCE_MS = 500L |
| 34 | + |
25 | 35 | @Single |
26 | | -class AndroidAppWidgetUpdater(private val context: Context) : AppWidgetUpdater { |
| 36 | +class AndroidAppWidgetUpdater(private val context: Context, stateProvider: LocalStatsWidgetStateProvider) : |
| 37 | + AppWidgetUpdater { |
| 38 | + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) |
| 39 | + |
| 40 | + init { |
| 41 | + // Observe state changes and trigger a widget re-render whenever the data changes. |
| 42 | + // Glance compositions are ephemeral — the widget cannot self-update via collectAsState() |
| 43 | + // alone, so we must call updateAll() externally to drive re-renders. |
| 44 | + @OptIn(FlowPreview::class) |
| 45 | + scope.launch { |
| 46 | + stateProvider.state |
| 47 | + .debounce(WIDGET_UPDATE_DEBOUNCE_MS) |
| 48 | + .distinctUntilChanged { old, new -> old.copy(updateTimeMillis = 0) == new.copy(updateTimeMillis = 0) } |
| 49 | + .collect { if (hasWidgetInstances()) updateAll() } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + private suspend fun hasWidgetInstances(): Boolean = |
| 54 | + GlanceAppWidgetManager(context).getGlanceIds(LocalStatsWidget::class.java).isNotEmpty() |
| 55 | + |
27 | 56 | override suspend fun updateAll() { |
28 | | - // Kickstart the widget composition. |
29 | | - // The widget internally uses collectAsState() and its own sampled StateFlow |
30 | | - // to drive updates automatically without excessive IPC and recreation. |
31 | 57 | @Suppress("TooGenericExceptionCaught") |
32 | 58 | try { |
33 | 59 | LocalStatsWidget().updateAll(context) |
34 | 60 | } catch (e: Exception) { |
35 | | - co.touchlab.kermit.Logger.e(e) { "Failed to update widgets" } |
| 61 | + Logger.e(e) { "Failed to update widgets" } |
36 | 62 | } |
37 | 63 | } |
38 | 64 | } |
0 commit comments