Michael Bichlmeier
06/29/2022, 7:13 AM@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.