Michael Bichlmeier

06/29/2022, 7:13 AM
I’m failing to implement a ContentViewed event inside my composable as I have the following requirements: • Should get triggered when the composable gets displayed • Should get triggered when you are navigating back to that composable (like opening a new compose screen and do a back press) • Should NOT get triggered on configuration changes (e.g. orientation)
fun MyScreen(viewModel: MyViewModel = get()){
   val items by viewModel.itemsToDisplay.collectAsState(initial = emptyList())


   // when the UI is displayed, the VM should track ContentViewed (only once)
   LaunchedEffectContentViewed { viewModel.trackContentViewed() }

private fun LaunchedEffectContentViewed(track: () -> Unit) {
    val config = LocalConfiguration.current
    var initialOrientation by rememberSaveable { mutableStateOf(config.orientation) }
    val orientationChanged = initialOrientation != config.orientation 

    var wasExecuted by rememberSaveable { mutableStateOf(false) }
    LaunchedEffect(Unit) {
       if (!wasExecuted) {
         if (!orientationChanged) track() // only track when orientation change was not the reason for recomposition
         wasExecuted = true

       if (orientationChanged) {
            initialOrientation = config.orientation // update initialOrientation with new one 
I’m quite sure I’m doing something wrong with my
calls and I hope some can explain me what I have to adapt to achieve my requirements? I also created a stackoverflow question for that.