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?
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()
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With