Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a kotlin MutableStateFlow without an initial value

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

like image 709
Kratos Avatar asked Mar 15 '26 23:03

Kratos


1 Answers

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 SharedFlow

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.

like image 90
Jolan DAUMAS Avatar answered Mar 17 '26 13:03

Jolan DAUMAS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!