android 可变状态流合成中出现并发修改异常

gjmwrych  于 2023-03-21  发布在  Android
关注(0)|答案(1)|浏览(110)

同时更新/使用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属性,但是如何解决呢?

rt4zxlrg

rt4zxlrg1#

该问题的解决方案是将调度程序从Main(如果未设置,则为默认调度程序)更改为某个后台调度程序,即:IO
private fun getItems() = viewModelScope.launch(Dispatchers.IO) {
工作起来像一个魅力

相关问题