Does anyone know if there’s an equivalent of the S...
# compose
m
Does anyone know if there’s an equivalent of the SwiftUI onAppear for compose? I have a custom modifier i’m using for whole pages, but it basically just fires only the first time something enters the composition. So it works well for full pages, but if i want to fire it for portions of a page in say a LazyColumn it’s not really what we want.
s
LaunchedEffect(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.
m
Unfortunately
LaunchedEffect
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:
Copy code
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
}
I’m using that in a
composed
modifier to manage whether something has been seen or not, get the layout coordinates, collect the state, etc…
180 Views