Search code examples
androidkotlinkotlin-flow

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


Solution

  • 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.