Jetpack compose scroll listener

Viewed 4316

Is there a way by which I can log an event when scrolling in a Column? I made it scrollable, saved the scroll state, but I can't find where to call a lambda function given as param to composable onScroll: () -> Unit

3 Answers

You can observe the scrollState:

 val scrollState = rememberScrollState()
 Column(
    modifier = Modifier
        .verticalScroll(scrollState)
)

You can check the value of this scrollState:

if (scrollState.isScrollInProgress){
    println("scrolling")
}

In case you need to wait for the scroll is completed, you can use if + DisposableEffect:

if (scrollState.isScrollInProgress) {
    DisposableEffect(Unit) {
        onDispose {
            println("scroll completed")
        }
    }
}

If you wondering how to do this in a LazyColumn:

val nestedScrollConnection = remember {
  object : NestedScrollConnection {
      override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
          // On scroll ended detection
          println("scroll completed")
          return super.onPostFling(consumed, available)
      }
  }
}

and

LazyColumn(
    modifier = Modifier.nestedScroll(nestedScrollConnection)
)

There's a property on scroll state called isScrollInProgress. That one can be used. If isScrollInProgress is true i called my own lambda function onScroll(). Works fine.

Related