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)
){
...
}
theapache64
11/08/2022, 2:16 PMMyViewModel
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 PMdewildte
11/08/2022, 2:20 PMViewModel
this way is not the proper way to use it.dewildte
11/08/2022, 2:20 PMViewModel
is recommended to be used at the Screen Level not lower then that.dewildte
11/08/2022, 2:21 PMViewModel
can be observed and passed down to @Composable
s in the screen.dewildte
11/08/2022, 2:25 PMLazyColumn{
val myDataSet = viewModel.dataSet
...
items(items = myDataSet) { itemState ->
MyItem(myItemState = itemState)
}
}
@Composable
fun MyItem(
myItemState: MyItemState
){
...
}
dewildte
11/08/2022, 2:25 PMLazyColumn
is in the screen level @Composable
dewildte
11/08/2022, 2:27 PMdewildte
11/08/2022, 2:31 PMMyItemState
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.dewildte
11/08/2022, 2:34 PMMyViewModel(itemA)
should be structurally equal.dewildte
11/08/2022, 2:35 PMMyViewModel(itemA) == MyViewModel(itemA)
should be true
dewildte
11/08/2022, 2:35 PMAlbert 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.Albert Chang
11/08/2022, 2:38 PMMyViewModel(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.