Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a generic declared Kotlin MutableStateFlow

Im investigating Kotlin MutableStateFlow/StateFlow and would like to declare my MutableStateFlow in a Generic Base Class as follows:-

class MyBaseClass<S> {

private val internalState = MutableStateFlow<S>(//WHAT GOES HERE????//)

    val state: StateFlow<S>
        get() = internalState

}

The issue I am stuck with is that MutableStateFlow has a mandatory initial value.

I cannot see how to provide a generic initial value of Type "S"

Is it possible to use this approach of employing a generic base class instance variable?

like image 315
Hector Avatar asked Nov 15 '25 23:11

Hector


2 Answers

Building up on Harshith Shetty answer all I did differently was to initialize the internalState as lazy so I can avoid the accessing non-final property in constructor warning

abstract class MyBaseClass<S> {

    abstract val initialState: S

    private val internalState: MutableStateFlow<S> by lazy { MutableStateFlow(initialState) }

    val state: StateFlow<S>
        get() = internalState

}

Btw there is no way to inizialize MutableStateFlow without initial value. If you absolutely do not want an initial value use ConflatedBroadcastChannel instead.

e.g.

val internalState: ConflatedBroadcastChannel<S> = ConflatedBroadcastChannel()

like image 165
ThanosFisherman Avatar answered Nov 18 '25 12:11

ThanosFisherman


You can take the default initial state value from derived class like,

abstract class MyBaseClass<S> {

    abstract val initialState: S

    private val internalState = MutableStateFlow<S>(initialState)

    val state: StateFlow<S>
        get() = internalState

}
like image 35
Harshith Shetty Avatar answered Nov 18 '25 13:11

Harshith Shetty



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!