Hello everyone! Has anyone ever tried creating com...
# compose-android
s
Hello everyone! Has anyone ever tried creating composables that instantiate their own ViewModel? I’m working on a
LazyColumn
that displays several composables, and I’d like each of them to manage their own logic independently. My use case: Each composable in the list has its own state — for example, a “like” button that can be either active or inactive. I think it would make sense for each item to have its own ViewModel, so it can connect to the Room database and manage its own state. I’ve tried a few approaches, but haven’t had much luck so far. I’d love to hear if anyone has tackled something similar and what worked for you. Thanks in advance!
p
You need to hoist each component state outside of the LazyColumn, better to hoist it in the LazyColumn's parent Composable. On another note, the LazyColumn will detach/reattach you component view(the composable) anytime it goes off the screen viewport and comes back. This behavior can be tricky to track the lifecycle of such Composable. To achieve that what I do is creating a stateful class to keep the history of the Composable start/stop and such. This class instance lives in the ViewModel itself
s
Sounds very interesting but it seem a little complex to the solution that i would like (ideally) to apply. I guess I would take another way with that but I take in consideration your solution for the future. Thank you so much!!
👍 1
p
No worries, there're many ways to tackle this behavior, the detached/reattach inside the LazyColumn.
s
yeah,,, and its a shame that´s not something easy to do..
p
There is not right or at least there is no consistent workaround for this particular case
c
I still feel like this is one of those things where you dont want each composable to instantiate their own VM. You want events up and state down. While "convenient" to have each one connect to room and manage its own state, everything else about it gets a bit more inconvenient. like testing, or writing previews.
s
Yeah, I have mixed feelings about this… I’m not even sure it’s a good approach in terms of performance. Instantiating a ViewModel every time a Composable is created might be a bit heavy. It’s great to hear your thoughts, guys — thanks a lot! 🙂