@Composable
private fun TestScreenA() {
val myItems = remember { mutableStateOf(listOf("A", "B", "C", "D")) }
TestList(
myItems = myItems.value,
onClick = { clickedItem ->
// for demonstration purposes we remove item on click
myItems.value = myItems.value.filterNot { it == clickedItem }
}
)
}
选项B:将状态保留在视图模型中(和之前一样)
class TestViewModelB: ViewModel() {
private val _myItems = MutableStateFlow(listOf("A", "B", "C", "D"))
val myItems = _myItems.asStateFlow()
fun onItemClicked(clickedItem: String){
// for demonstration purposes we remove item on click
_myItems.update { items -> items.filterNot { it == clickedItem } }
}
}
@Composable
private fun TestScreenB(
// inject viewModel here using your favorite DI-Framework
viewModel: TestViewModelB
) {
TestList(
// you might want to use collectAsStateWithLifecycle in the future
// see https://medium.com/androiddevelopers/consuming-flows-safely-in-jetpack-compose-cde014d0d5a3
myItems = viewModel.myItems.collectAsState().value,
onClick = viewModel::onItemClicked
)
}
1条答案
按热度按时间wfsdck301#
摆脱recyclerview的臃肿是我最喜欢compose的优点之一,让我们假设你想在屏幕上包含以下列表:
选项A:将状态保持在可组合状态。
选项B:将状态保留在视图模型中(和之前一样)
这两个选项都是可行的(特别是在使用
rememberSavable
时)。然而,我建议刚迁移到编写的人使用选项B,因为它更类似于他们所使用的。我个人使用选项A用于简单的状态,选项B用于更复杂的状态(如列表)