'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?



Solution 1:[1]

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()

Solution 2:[2]

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

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Harshith Shetty