Two Horses
Two Horses

Reputation: 1692

What's the difference between using remember in assignment vs in delegation in Jetpack Compose?

I'm learning Compose and wondering what's the difference between these two lines of code:

val stateValue = remember { mutableStateOf("value") }

And:

var stateValue by remember { mutableStateOf("value") }

In the first method, the way we update the state is by changing the value like so:

stateValue.value = "new value"

But when using delegation wer'e just changing the variable's value directly:
stateValue = "new value"

How then after re-composition the state is still "remembered" after we just overridden the existing value that had the remember function?

Upvotes: 2

Views: 1065

Answers (1)

Joffrey
Joffrey

Reputation: 37710

Delegation -as the name says- allows to delegate the getter and setter to a separate object.

So when you do stateValue = "new value" on the delegated property, you are not "overriding the existing value that had the remember function". What happens is that the assignment syntax actually calls the setValue() operator on the property delegate (the instance returned by the call to remember that was done during initialization of the property).

Take a look at the documentation to learn more about delegated properties: https://kotlinlang.org/docs/delegated-properties.html

Upvotes: 2

Related Questions