Nav*_*eed 5 android concurrentmodification kotlin
的文档SnapshotStateList
指出它类似于常规的可变列表。我有一个用例,我需要修改列表 ( ) 中的所有元素set case
。这不会改变列表的大小,但我遇到了 ConcurrentModificationException。
我在这里创建了一个非常简化的用例版本。以下 kotlin 列表运行良好:
val myList2 = mutableListOf("a", "b", "c")
myList2.forEachIndexed { index, _ ->
// Modify item at index
myList2[index] = "x"
}
Run Code Online (Sandbox Code Playgroud)
但我在这里遇到并发修改异常:
val myList = mutableStateListOf("a", "b", "c")
myList.forEachIndexed { index, _ ->
// Modify item at index but I get an exception
myList[index] = "x"
}
Run Code Online (Sandbox Code Playgroud)
如何修改mutableStateList()
in place 的所有元素而不出现并发修改异常?
编辑:
我可以创建一个副本mutableStateList
来迭代它,它工作得很好,但由于我没有更改列表的大小,是否可以就地执行它?
一些可能的解决方法是replaceAll
就地转换列表(只要您不需要索引),或者如果需要,则仅对索引使用老式循环
val listA = mutableListOf("A","B","C")
// this works
listA.forEachIndexed { i, s ->
listA[i] = s.lowercase()
}
val listB = mutableStateListOf("A","B","C")
// this fails - as you noted
listB.forEachIndexed { i, s ->
listB[i] = s.lowercase()
}
// this works, as long as you don't need the index
listB.replaceAll { s -> s.lowercase() }
// this also works, and lets you have the index
for(i in listB.indices) {
listB[i] = listB[i].lowercase()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1247 次 |
最近记录: |