DEV Community

Zach Klippenstein
Zach Klippenstein

Posted on • Edited on • Originally published at blog.zachklipp.com

remember { mutableStateOf() } – A cheat sheet

This post has moved to blog.zachklipp.com.

Top comments (7)

The discussion has been locked. New comments can't be added.
Post has moved to https://blog.zachklipp.com/remember-mutablestateof-a-cheat-sheet/
Collapse
 
louiscad profile image
Louis CAD

If I make an interface of val properties, and implement it with a class that delegates these to a Compose State/MutableState, I'll not get the observability for Composable functions because, and the only way through is to expose State<T> instead of T, right?

Collapse
 
zachklipp profile image
Zach Klippenstein

Nope, that still works. Reads are tracked by actual calls to the getter of a State.value, no matter where or how it is called. Also, there’s no compiler magic here. I believe under the hood there is actually a thread local installed that points to the current snapshot and reads record themselves there. So it doesn’t matter what your call stack looks like.

Collapse
 
louiscad profile image
Louis CAD

Oh, that's very neat!
Thanks for the info. I hope this knowledge makes it into the official docs.

Collapse
 
danielrendox profile image
Daniel Rendox

So what actually happens when the following code is executed:

var text by remember { mutableStateOf("") }
Enter fullscreen mode Exit fullscreen mode

1) A new object of the type MutableState<String> is created. This object holds the value (in our case empty string). And whenever the value changes, MutableState tells Android to recompose the UI.
2) Thanks to remember, the object of the MutableState is cashed and therefore will not get recreated every recomposition.
3) by tells the compiler to "link" var text with the value that the MutableState object holds. Whenever our text is updated, that value will be updated either automatically.

🙏 Correct me if I'm wrong

Collapse
 
hakanai profile image
Hakanai • Edited

There's also this form.

@Composable
fun MyField() {
    val (text, setText) = remember { mutableStateOf("") }
    TextField(text, setText)
}
Enter fullscreen mode Exit fullscreen mode

It really makes me wish they'd have an overload which just takes MutableState<String> so that I can just pass the state object itself, or some kind of adapter.

For whatever reason, Jetpack Compose seem to really love passing the value and the way to update the value as two different thingies, when they could have been bundled together as a single concept.

Collapse
 
bubenheimer profile image
Uli Bubenheimer

"remembered values can be notified when they enter and leave a composition": can you give a pointer what you are referring to?

Collapse
 
zachklipp profile image
Zach Klippenstein