I am trying to load list of data in App Widget using jetpack compose and i have stored in Room Local database, how i can retrive the data in GlanceAppWidget class.
I am trying to load list of data in App Widget using jetpack compose and i have stored in Room Local database, how i can retrive the data in GlanceAppWidget class.
You need to work with GlanceAppWidgetReceiver class. You can create coroutine and access your domain layer. After that, you can find your GlanceAppWidget class and send your data your widget class. Please have look this article to full example : https://medium.com/better-programming/android-jetpack-glance-for-app-widgets-bd7a704624ba
@AndroidEntryPoint
class MarketWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = MarketWidget()
private val coroutineScope = MainScope()
@Inject
lateinit var marketInformationUseCase: MarketInformationUseCase
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
observeData(context)
}
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (intent.action == MarketRefreshCallback.UPDATE_ACTION) {
observeData(context)
}
}
private fun observeData(context: Context) {
coroutineScope.launch {
val marketInformation =
marketInformationUseCase.getMarketInformation(MarketInformationTimespan.TIMESPAN_1DAYS)
val glanceId =
GlanceAppWidgetManager(context).getGlanceIds(MarketWidget::class.java).firstOrNull()
glanceId?.let {
updateAppWidgetState(context, PreferencesGlanceStateDefinition, it) { pref ->
pref.toMutablePreferences().apply {
this[currentPrice] =
marketInformation.currentPrice
this[changeRate] =
marketInformation.changeRate
this[isChangeRatePositive] =
marketInformation.changeStatus == MarketInformationChangeStatus.POSITIVE
}
}
glanceAppWidget.update(context, it)
}
}
}
companion object {
val currentPrice = stringPreferencesKey("currentPrice")
val changeRate = stringPreferencesKey("changeRate")
val isChangeRatePositive = booleanPreferencesKey("isChangeRatePositive")
}
}