https://kotlinlang.org logo
#compose
Title
# compose
d

Divyansh Kushwaha

11/22/2023, 9:46 AM
I have this code in my DashboardScreen() composable. It basically allows to perform a sync whenever the activity is launched with
ACTION_LAUNCH_WITH_SYNC
(using a notification, to be specific). But the issue is whenever I navigate to another screen and navigate back to the dashboard,
ON_CREATE
is emitted again. It should only be called, whenever activity's onCreate is called, right?
Copy code
DisposableEffect(Unit) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_CREATE) {
                Timber.d("Dashboard: CREATED")
                if (activity.intent.action == MainActivity.ACTION_LAUNCH_WITH_SYNC) {
                    viewModel.startDashboardSync(null)
                }
            }
        }
        activity.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
a

Alex

11/22/2023, 10:27 AM
This works as designed, it will trigger everytime the composable is rendered first but only after onCreate
Do you also intend to sync when the device is rotated, e.g. on configuration changes or do you only want to sync when the activity is created for the first time?
d

Divyansh Kushwaha

11/22/2023, 10:53 AM
When (Activity is created for the first time) && (action is LAUNCH_WITH_SYNC)
i

Ian Lake

11/22/2023, 3:33 PM
Any LifecycleEventObserver you add is always "caught up" to what state you're in (that way you're guaranteed to get an ON_CREATE before an ON_START, etc. and the reverse the other way down) so you'd need to track if this is the first time you've received a particular event separately
👍🏼 1
2 Views