如何避免MutableStateFlow Kotlin中的默认值
我在项目中使用MutableStateFlow。当我们初始化mutableStateFlow对象时,我们需要给出默认值。
val topics = MutableStateFlow<List<String>>(emptyList())
当我收集此值时,
[null, "Hello", "world"]
我想在适配器中通过此列表。因此,有什么方法可以在传递适配器之前删除空对象,还是有更好的方法?
viewModel.topics.collect { topicsList ->
println(topicsList) // [null, "Hello", "world"]
adapter.submitList(topicsList)
}
I am using MutableStateFlow in my project. When we initialise the MutableStateFlow object we need to give default value.
val topics = MutableStateFlow<List<String>>(emptyList())
when I collect this value
[null, "Hello", "world"]
I want to pass this list in adapter . So is there a way we can remove the null object before passing in adapter or Is there any better way ?
viewModel.topics.collect { topicsList ->
println(topicsList) // [null, "Hello", "world"]
adapter.submitList(topicsList)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您不希望它具有强制性初始值,请改用mutableSharedFlow。如果您给它
replay = 1
,onbufferoverflow = bufferoverflow.drop_oldest
和distractununtilChanged()
,它基本上是与没有sutableStateFlow的情况执行value
。如果onbufferoverflow
不是bufferoverflow.suspend
,tryemit
将始终成功,以便您可以使用tryemit()
而不是value =
。If you don't want it to have an enforced initial value, use MutableSharedFlow instead. If you give it
replay = 1
,onBufferOverflow = BufferOverflow.DROP_OLDEST
, anddistinctUntilChanged()
, it's basically the same thing as a MutableStateFlow without the enforcedvalue
. And ifonBufferOverflow
is notBufferOverflow.SUSPEND
,tryEmit
will always succeed so you can usetryEmit()
instead ofvalue =
.由于它发出了字符串列表,因此您可以尝试以null这样的null初始化状态流
,当您收集时,您可以检查发射值是否为null
Since it emits a list of strings you could try to initialise the StateFlow with a null like so
And when you collect you can check if the emitted value is null or not
如果要忽略状态流的初始值,请设置初始值
null
或任何您想要的任何内容。然后,您可以在Flow上使用过滤器
函数。例如,初始值是
null
输出
If you want to ignore initial value of StateFlow, set initial value
null
or anything you want. Then you can usefilter
function on flow.For example initial value is
null
Output
如果我们给出了一个普通的通用类型密封类。
普通密封类
在这种情况下,我们可以设置这样的初始值。
packageModel 是模型/pojo类
If we have given a common generic type sealed class.
Common Sealed Class
In that case, we can set the initial value like this.
PackageModel is Model/Pojo class
您只需使用
drop(1)
:You can simply ignore the first value by using
drop(1)
:我认为您需要的是:
I think what you need is this: