Is there a way of performing a function call when a MutableState of variable changes in Jetpack Compose

Viewed 1201

I have created a variable called currentlySelectedJobId, this allows me to capture the job Id when the user has selected it elsewhere in my code.

When this happens i would like to scroll my LazyRow of items to this object.


LazyRow(state = scrollState) {
items(....
......
}

However I am struggling to see a way to capture the change of currentlySelectedJobId and perform the action scrollState.animateScrollToItem(index = 0)

Is there a way to do this ?

2 Answers

You can use LaunchedEffect with your variable as a key: it'll be called each time the key is different since latest recomposition.

LaunchedEffect(currentlySelectedJobId) {
    scrollState.animateScrollToItem(index = 0)
}

This will also be called on the initial recomposition too, so depending on your code you may need to skip this initial call.

Try this

@Composable
fun List(
currentlySelectedJobId: Int, //Pass a 'delegated' MutableStateValue here
state: //... The last scroll state
){
 LaunchedEffect(currentlySelectedJobId){
  state.animateScrollToItem(currentlySelectedJobId)
 }
}

LaunchedEffect here is used to trigger a function only once per composition or when the key changes. I passed the key as the job id (assuming it is the same as the index), then animated to that value.

You can read more about LaunchedEffect and other side-effects

Related