英文:
Can I use MutableStateFlow(mutableListOf<Int>()) launch a Flow collect?
问题
我知道我可以在 Code B 中使用 mutableStateListOf 更改 state。
在 Code A 中,我可以使用 MutableStateFlow(mutableListOf<Int>()) 创建一个 Flow,然后进行 Flow 的收集吗?
如果不能,是否有类似 mutableStateListOf 的 Flow 函数?
英文:
I know I can change the state with mutableStateListOf in Code B.
Can I use MutableStateFlow(mutableListOf<Int>()) launch a Flow collect in Code A?
If not, is there a similar Flow function just like mutableStateListOf ?
Code A
val stateFlow = MutableStateFlow(mutableListOf<Int>())
stateFlow.value.add(1)
stateFlow.value.add(2)
Code B
val listExpandedMInfoID = mutableStateListOf<Int>()
listExpandedMInfoID.add(mInfo.id)
答案1
得分: 2
StateFlow如果与任何可变类一起使用,包括MutableList,它会出现问题。它无法检测到列表的更改,因此如果您对其进行了更改,它将不会再次发射该列表。
没有mutableStateListOf()的Flow模拟版本。如果您使用StateFlow,必须使用只读列表才能使其正常工作。对于其他Flow,您可以使用可变列表,但每次修改后都必须再次发射它。
除非您的列表非常庞大,否则列表副本通常不会很昂贵。
英文:
StateFlow breaks if you use it with any mutable class, including MutableList. It cannot detect a change in the list so it will not emit the list again if you mutate it.
There is no Flow analog of mutableStateListOf(). If you use StateFlow, you have to use read-only Lists for it to work. With other flows, you could use a mutable list but you would have to emit it again each time it’s modified.
List copies are not expensive anyway unless your List is enormous.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论