mattinger
03/09/2023, 10:16 PMStylianos Gakis
03/09/2023, 10:41 PMLaunchedEffect(Unit) {}
should be your “do something on first composition and never again” thing, but not quite following the rest of the explanation you’re giving.mattinger
03/09/2023, 11:16 PMLaunchedEffect
does not meet the requirements of what we’re looking for. That will fire whenever something first enters the composition. I need something that fires when at least 1 pixel of the element is actually visible to the user. I think i’ve figured it out sort of. I made a modifier that will use the onGloballyPositioned callback to monitor the state.
Whenever that fires, i can check to see if the LayoutCoordinates intersect the LayoutCoordinates of the root composable. It’s a variant of a different modifier i have that is more meant for full screen things rather than individual elements:
private fun LayoutCoordinates.isAtLeastPartiallyVisible(view: View): Boolean {
if (!isAttached) return false
// Window relative bounds of our compose root view that are visible on the screen
val globalRootRect = android.graphics.Rect()
if (!view.getGlobalVisibleRect(globalRootRect)) {
// we aren't visible at all.
return false
}
val root = findRootLayoutCoordinates()
val positionInRoot = positionInRoot()
val rootRect = android.graphics.Rect().apply {
left = 0
right = root.size.width
top = 0
bottom = root.size.height
}
val itemRect = android.graphics.Rect().apply {
left = positionInRoot.x.toInt()
right = positionInRoot.x.toInt() + size.width
top = positionInRoot.y.toInt()
bottom = positionInRoot.y.toInt() + size.height
}
val isPartiallyVisibile = itemRect.intersect(rootRect)
return isPartiallyVisibile
}
mattinger
03/09/2023, 11:18 PMcomposed
modifier to manage whether something has been seen or not, get the layout coordinates, collect the state, etc…