When I have this bit of code ```MyComposable(stat...
# compose
When I have this bit of code
Copy code
MyComposable(state, onClick = { someObject.sendEvent() })
is immutable, but
is not `Stable`/`Immutable`, (for example it can be a
) this leads to constant recompositions, because
is not considered a
lambda. I confirmed this: my code stops constantly recomposing
if I make
empty. What is the recommended refactoring to avoid such issues? Marking
as Stable is not always possible or often incorrect.
This article helped me remember this issue, I now went and re-read its corresponding recommendation section on how to handle this problem. thanks!
I've used a combination of method-references and remembering lambdas and it seems to help. This stuff is really not obvious I hope in future tooling can somehow hint about this.
How far does this stretch? As an example, consider a "viewmodel" that lives outside of compose and provides a
(Event) -> Unit
callback for every state it produces. The lambda encapsulates some repository which is unstable. So the lambda is now unstable as well? ­čĄö
I find it best to think of this in terms of lambda being compiled to class instance:
Copy code
class SomeLambda(val viewModel: ViewModel) {
  fun invoke() {
if you have something like this, then repostitory will not be a property of SomeLambda class, so it will not pariticipate in compose's desicion on wheter
onClick: SomeLambda
argument is stable or not.
Thats a great way to put it! Given that the viewmodel is also unstable, I take it that the lambda will be unstable all the time as well. This is a bit of a surprise to me, but it makes sense. The article mentions that you can work around this by remembering the lambda. Using the same example I gave above, if the viewmodel instead declares the lambda (rather than creating a new one for each state), that should give the same result?
depends on the key to remember
Its both scary and awesome to think that such a small tweak can make such a big difference in the world of compose. I wouldve never thought that this was the reason why some of my animations werent super-smooth (I posted about it the other day). Changing from a fun interface that accepts <Event> to a value class that wraps a lambda made a huge difference for me. It did not make any difference whether I was creating them on the fly or keeping the same instance around in the class (or remembered). Thanks for bringing this to my attention! fist bump