Hello, does anyone understand when you should use ...
# compose
j
Hello, does anyone understand when you should use viewmodel + mutablestateOf() vs. using remember?
n
I hardly use
mutableStateOf
in any composable. All states and events are hosted in the viewModel and exposed with
flows
.
โž• 2
j
But do you use remember? I'm confused about how viewmodel interacts with remember, or if you only use one or the other.
n
Nope haven't used yet in any of my projects. But when something is really really local to a specific composable then you may use remember.
n
remember is for managing state inside of a composable. You won't (and can't) use remember inside of your view model.
๐Ÿ‘ 1
โ˜๏ธ 2
An example is you might have a composable with an expanded state which you don't hold on the view model. Inside of the composable you can then go
val isExpanded = remember { mutableStateOf(false)}
This state can then be updated independent of your view model. Overall what you put inside your view model vs what you keep inside a composable comes down to what it is and what architecture you are going for.
j
@Nathan Castlehow Thanks Nathan, I read the article. I guess what I am trying to understand is whether there are cases when you would both pass a viewmodel to your composable function, and use remember inside the composable. Is correct to say that you can, but as @nilTheDev menitoned, that would only be for variable that are only changed locally in the composable and are not related to the viewmodel?
n
Yeah that sounds about right ๐Ÿ™‚. For example you might remember a card expanded state inside of a card composable (doesn't have to be but for the sake of this lets say it is) but the data for the card (say an image and a description) would come from my viewmodel.
๐Ÿ‘ 1
๐Ÿ™‡โ€โ™‚๏ธ 1
s
@John Aoussou This 5 part series from @Zach Klippenstein (he/him) [MOD] helped me A LOT to deepen my knowledge regarding state, remember, and all the likes https://dev.to/zachklipp/remember-mutablestateof-a-cheat-sheet-10ma
๐Ÿ™‡โ€โ™‚๏ธ 1
๐Ÿ‘ 1
z
There was a really good talk at ADS that talked about state management and when to use ViewModels too:

https://www.youtube.com/watch?v=rmv2ug-wW4Uโ–พ