Reputation: 297
I am looking for a way to display list of items where each item also contains a list. Following examples are from a test app, not a real one.
Two classes. Group can contains N number of Devices
data class Group(
var name: MutableState<String> = mutableStateOf(""),
var devices: MutableList<Device> = mutableListOf()
)
data class Device(
val name: MutableState<String> = mutableStateOf("")
)
Now I need to render a list of Groups and all devices inside a group.
LazyColumn {
items(vm.groups) {
Column {
Text("Group: ${it.name.value}")
Text("Devices inside : ${it.devices.count()}")
Divider()
Spacer(modifier = Modifier.height(10.dp))
it.devices.forEach {
Row {
Spacer(modifier = Modifier.width(20.dp))
Text("Devices name : ${it.name.value}")
}
}
Spacer(modifier = Modifier.height(10.dp))
Divider()
}
}
}
Everything works as expected except the internal list. If I add new device into existing group, UI will not recompose that part. In real application devices can come and go into exiting groups, new groups can appear and disappear.
Is it even possible for UI to observe changes in internal List of devices or some sort of trick should be used like making copy of Group.devices list and assign to same devices property with new device added?
Upvotes: 2
Views: 3694
Reputation: 92
An alternate way to implement this is to use a viewmodel:
data class Device(
val name: String
)
@HiltViewModel
class ExampleViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val _deviceList = mutableStateListOf<Device>()
val deviceList: SnapshotStateList<Device> = _deviceList
}
It's better to separate data and business logic.
Upvotes: 0
Reputation: 297
I think I found solution.
data class Group(
var name: MutableState<String> = mutableStateOf("")
) {
private var _devices : MutableList<Device> = mutableStateListOf()
var devices : List<Device> by mutableStateOf(_devices)
fun addNewDevice(device: Device) {
_devices.add(device)
}
}
This class works perfectly
Upvotes: 1