I have this code in my DashboardScreen() composabl...
# compose
d
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
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
When (Activity is created for the first time) && (action is LAUNCH_WITH_SYNC)
i
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