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

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)
Copy code
@Composable
fun MyScreen(viewModel: MyViewModel = get()){
   val items by viewModel.itemsToDisplay.collectAsState(initial = emptyList())

   ItemList(items)

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


@Composable
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
remember*
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.
5 Views