Can I use MutableStateFlow(mutableListOf<Int>()) launch a Flow collect?

huangapple go评论56阅读模式
英文:

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&lt;Int&gt;()) launch a Flow collect in Code A?
If not, is there a similar Flow function just like mutableStateListOf ?

Code A

val stateFlow = MutableStateFlow(mutableListOf&lt;Int&gt;()) 

stateFlow.value.add(1)
stateFlow.value.add(2)

Code B

val listExpandedMInfoID = mutableStateListOf&lt;Int&gt;()
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.

huangapple
  • 本文由 发表于 2023年6月9日 11:00:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定