What's the recommended way to collect broadcast re...
# compose-android
a
What's the recommended way to collect broadcast receiver events in Compose? produceState with awaitDispose to unregister receiver?
c
Please do not cross-post to multiple channels with already ongoing discussion; https://kotlinlang.slack.com/archives/CJLTWPH7S/p1772360879279979
a
i moved the thread here because it was wrong channel before, damn this slack is pissing me off already
1
m
My gut instinct is to receive the broadcasts anywhere other than a composable. What specific broadcast do you have in mind, and why is the UI layer involved?
c
well you did not “move” it, you copy/pasted it 😉
a
you responded to old thread too
well
anyways, here's what i had in mind: class SystemTimeZoneObserver : TimeZoneObserver { @Composable override fun rememberTimeZone(): TimeZone { val context = LocalContext.current return produceState(initialValue = TimeZone.currentSystemDefault()) { val receiver = object : BroadcastReceiver() { override fun onReceive(ctx: Context?, intent: Intent?) { value = TimeZone.currentSystemDefault() } } val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED) filter.addAction(Intent.ACTION_TIME_CHANGED) filter.addAction(Intent.ACTION_DATE_CHANGED) context.registerReceiver(receiver, filter) awaitDispose { context.unregisterReceiver(receiver) } } .value } } thought of using it in presenters, however putting it in repos and collecting flow as state is probably better.
👍🏻 1
j
I'd recommend using a
callbackFlow
to "convert" the broadcast receiver into a Flow and then use
collectAsStateWithLifecycle(initialValue = SOMETHING)
to collect from it in Compose. I recommend declaring the
callbackFlow
in a VM or a repo so that it doesn't get recreated if/when your screen leaves composition.
👍 1
👍🏾 1