同时更新/使用MutableStateFlow
时出现ConcurrentModificationException
,如何防止?
代码片段:
class SearchViewModel() : ViewModel() {
val searchState = MutableStateFlow(SearchState())
private fun getItems() = viewModelScope.launch {
....
object : Callback<Results> {
override fun publish(items: Results): Boolean {
searchState.value = searchState.value.copy( // <--- ConcurrentModificationException at emit() function
currentItems = items
)
}
}
}
@Composable
fun ScreenContent(viewModel: SearchViewModel) {
val state by viewModel.searchState.collectAsState()
Column(
modifier = Modifier.fillMaxWidth()
) {
// \/ ConcurrentModificationException here sometimes as well
state.currentItems.forEachIndexed { index, searchRowItemData ->
SearchRowItem(searchRowItemData, index == state.currentItems.lastIndex) {
onItemClicked(searchRowItemData)
}
}
}
}
我想问题是我同时更新和迭代searchState属性,但是如何解决呢?
1条答案
按热度按时间rt4zxlrg1#
该问题的解决方案是将调度程序从
Main
(如果未设置,则为默认调度程序)更改为某个后台调度程序,即:IO
private fun getItems() = viewModelScope.launch(Dispatchers.IO) {
工作起来像一个魅力