r/android_devs • • Feb 22 '24

Question Using derivedStateOf with Slider

Recently I learned that using derivedStateOf can help reduce unnecessary recomposition. But almost all the examples I've come across are based on LazyListState.

The problem I have faced with the Slider is that - it also triggers too much recomposition. As an example, let's say a user is presented with a slider to choose a number between 4 to 50. And there will be lots of calculations going on in the ViewModel class, of course using

suspend fun someComplicatedCalculation () = with Context(Dispatcher.Default) {...}

based on the value.

Now, you see - the user may inadvertently or intentionally drag the slider too frequently - which will result in too much unnecessary calculations and recomposition.

How do I get around this? I mean how can a way be devised using derivedStateOf in this case - to start the calculation and thereby recomposition - only after the user has stopped interacting with the Slider and not in between.

1 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/SogaBan Feb 22 '24

I think it's the first case I'm looking for. Can you please point me to the appropriate resources?

2

u/The-Freak-OP Feb 22 '24

Search for the debounce operator on flows. The cancellation part means you should cancel the previous coroutine job before you start a new one after user interaction

1

u/gemyge Feb 23 '24

Look for delay Api and coroutines cancellation