我想使用 StateFlow。但目前,我找不到任何可以帮助我的讲座。
我面临一个问题:首先,我有一个包含字符串列表的单例,我想要一些“容易”理解的东西,即使它不是现在的目标目的。目的是用字符串填充并发出列表(稍后它将是一个复杂的对象)。
class CustomStateFlow() {
private val _custom = MutableStateFlow(emptyList<String>())
val custom: StateFlow<List<String>> = _custom
fun addString(string: String) {
val tempList = _custom.value.toMutableList()
tempList.add(string)
_custom.value = tempList
}
Run Code Online (Sandbox Code Playgroud)
这似乎有效,但我不喜欢临时列表...没有,我无法触发片段中自定义的“收集”。
有没有办法在不使用 tempList 的情况下实现这一目标?
感谢您
我正在像这样创建 MutableStateFlow:
val intSet = MutableStateFlow(HashSet<Int>())
Run Code Online (Sandbox Code Playgroud)
稍后我想更新此流程中的集合:
intSet.value.add(0)
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用(集合更新,但观察者没有收到通知)。我发现它的工作方式:
val list = HashSet<Int>(intSet.value)
list.add(0)
intSet.value = list
Run Code Online (Sandbox Code Playgroud)
但它创建了该集合的副本,因此它看起来不适合我。有没有更简单的方法来更新 StateFlow 中的集合?