I want to track screen views in a compose-only app, so no activities, fragments, only composable functions.
When and how I should call the screen tracking e.g. for firebase?
Because the body of the composable function is executed on every recomposition, side effects can be also called repeatedly, and none of these means a real "view", composable can be invisible or just measured.
You can use LaunchedEffect or DisposableEffect with a constant key, for example Unit, to execute side effects exactly once a composable enters composition (and in the case of DisposableEffect also on exit), ignoring recompositions.
// I don't think PascalCase would suit this method, as it suggests an on-screen element
@SuppressLint("ComposableNaming")
@Composable
fun trackScreenView(name: String) {
DisposableEffect(Unit){
Log.d("SCREENTRACKING", "screen enter : $name")
onDispose { Log.d("SCREENTRACKING", "screen exit : $name") }
}
}
@Composable
fun Screen1() {
trackScreenView("Screen 1")
// your screen content here
}
@Composable
fun Screen2() {
trackScreenView("Screen 2")
// your screen content here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With