初始化kotlin mutableStateFlow而没有初始值

发布于 2025-02-01 20:27:48 字数 598 浏览 4 评论 0原文

我正在学习Kotlin流量,并在公司应用程序中慢慢将代码从Livedata转换为Kotlin Flow。因此,我有疑问:

在我的ViewModel中,我有这样的livedata变量“状态”:

var状态:mutableLivedAta = mutableLiveAtata()

,我在MainActivity中观察到了它。

现在我想用流量做同样的事情。我将所有发出/填充的零件和其他事物转换了,一切都很好,但是有一个问题。这是我的变量状态的一部分:

var状态:mutableStateFlow< status> = mutableStateFlow() - >此代码给出了错误。我需要在括号中传递参数的值,

所以我必须这样写:

var status: MutableStateFlow<Status> = MutableStateFlow(Status.Failure("adding value even though I don't want to")) 

有人可以解释我是否有任何方法可以像以前在Livedata中与以前相同的情况下的初始化而不提供初始值?谢谢

I am learning kotlin flow and slowly converting code in my company app from livedata to kotlin flow. So I have question:

In my Viewmodel I had livedata variable "status" like this:

var status: MutableLiveData = MutableLiveData()

and I observed it in MainActivity.

Now I want to do same thing with flow. I converted all emiting/colleting parts and other things and everything works fine, but have one problem. This is declaring part of my variable status:

var status: MutableStateFlow<Status> = MutableStateFlow() -> this code gives error. I need to pass value for parameter in the brackets

So I have to write it like this:

var status: MutableStateFlow<Status> = MutableStateFlow(Status.Failure("adding value even though I don't want to")) 

Can anyone explain me is there any way to initialize this same as before in livedata without providing initial value? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忆悲凉 2025-02-08 20:27:48

您不能,可变状态流需要初始值。

一种方法是设置此值,并用null启动。

但这是一个窍门,

,使用ShareFlow

private val _status = MutableSharedFlow<Status>() 
val status = _status.asSharedFlow()

使用频道

private val _status = Channel<Status>() 
val status = _status.receiveAsFlow()

根据您想要的内容,

有两种更好的方法,请选择共享流或频道。与频道不同,共享流允许多个订户。就您而言,共享流是必经之路。

You can't, Mutable stateFlow require an initial value.

One way is to set this value nullable and init it with null.

But it's a trick and there is two better ways

Using ShareFlow

private val _status = MutableSharedFlow<Status>() 
val status = _status.asSharedFlow()

Using Channel

private val _status = Channel<Status>() 
val status = _status.receiveAsFlow()

Depending on what you want, pick SharedFlow or Channel.

SharedFlow allow multiple subscribers unlike the channel. In your case, SharedFlow is the way to go.

青衫负雪 2025-02-08 20:27:48

您可以在mutableStateFlow中启用对null对象的支持,然后将其初始化为null变量:

val status: MutableStateFlow<Status?> = MutableStateFlow(null)

You can enable support for null objects in the MutableStateFlow type and initialize it to null variable:

val status: MutableStateFlow<Status?> = MutableStateFlow(null)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文