theapache64
11/08/2022, 2:08 PMViewModel
as @Stable
? What wud be the conditions to do that? (learning about Compose Stability)dewildte
11/08/2022, 2:11 PM@Stable
is usually used on classes that are passed in as state to a composable.
ViewModel
is not meant to be used as state, it is a state holder so I am not sure why you would need to tell compose that it is stable.theapache64
11/08/2022, 2:15 PM@Composable
s that are inside my LazyColumn
has its own ViewModel
. Since data comes from a SnapshotStateList
, every time I add a new item to the list causing a recomposition to all the children inside the LazyColumn
.
Structure
LazyColumn{
val myDataSet : SnapshotStateList
...
item(myDataSet){ item ->
MyItem(item)
}
}
@Composable
fun MyItem(
item : Item,
myViewModel : MyViewModel = createViewModel(item.key)
){
...
}
MyViewModel
from the MyItem
. Since all public properties are exposed via the compose State
, i was thinking why not declare it as @Stable
?dewildte
11/08/2022, 2:18 PMViewModel
this way is not the proper way to use it.ViewModel
is recommended to be used at the Screen Level not lower then that.ViewModel
can be observed and passed down to @Composable
s in the screen.LazyColumn{
val myDataSet = viewModel.dataSet
...
items(items = myDataSet) { itemState ->
MyItem(myItemState = itemState)
}
}
@Composable
fun MyItem(
myItemState: MyItemState
){
...
}
LazyColumn
is in the screen level @Composable
MyItemState
would ideally be an immutable data class
.theapache64
11/08/2022, 2:31 PMviewModel
. In my case, I want my composable to have its own viewModel to control itself. The composable viewModel will be responsible to define the behaviour of the composable. This is a bit different than the MVVM
arch we see.dewildte
11/08/2022, 2:33 PMViewModel
@Stable
and ensure it upholds the contract that @Stable
implies.MyViewModel(itemA)
should be structurally equal.MyViewModel(itemA) == MyViewModel(itemA)
should be true
Albert Chang
11/08/2022, 2:38 PMScrollState
and LazyListState
are both stable state holders.
I recommend that you start with compose compiler metrics and see why it’s not inferred as stable.MyViewModel(itemA) == MyViewModel(itemA)
is not necessary for it to be stable.theapache64
11/08/2022, 2:41 PM…with compose compiler metrics and see why it’s not inferred as stable.
unstable viewModel: MyViewModel? = @dynamic createViewModel(..)
Yes I did that, and its happening because viewModel
marked as unstableAlbert Chang
11/08/2022, 2:44 PMMyViewModel
is marked as unstable in classes.txt.