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 another way using channel and receive it as flow :

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