在StateFlow中操作集合的正确方法 [英] Proper way to operate collections in StateFlow

查看:143
本文介绍了在StateFlow中操作集合的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这样创建MutableStateFlow:

I'm creating MutableStateFlow like this:

val intSet = MutableStateFlow(HashSet<Int>())

稍后,我想在此流程中更新集合:

And in some moment later I want to update collection in this flow:

intSet.value.add(0)

这似乎不起作用(集合已更新,但未通知观察者). 我发现它起作用的方式:

And this doesn't seem to work (the collection updates, but observers are not notified). The way that I found it working:

val list = HashSet<Int>(intSet.value)
list.add(0)
intSet.value = list

但是它创建了集合的副本,因此对我来说不合适.有没有更简单的方法来更新StateFlow中的集合?

But it creates copy of the collection, so it doesn't look proper for me. Is there any simpler way to update collection in StateFlow?

推荐答案

MutableFlow不检查集合内容中的更改.仅当集合引用发生更改时,它才会发出更改.

MutableFlow does not check for changes in the content of collections. Only when the collection reference has changed it will emit the change.

使用不可变的Set并使用+=运算符添加新元素.基本上,这将创建新的Set并将触发更改.

Use immutable Set and use the += operator to add new elements. This will basically, create new Set and will trigger the change.

val intSetFlow = MutableStateFlow(setOf<Int>())
intSetFlow.value += 0

这篇关于在StateFlow中操作集合的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆