How to make flexible view models with composition over inheritance

open class ParentViewModel : ViewModel() {
private val _alertMessageState = MutableStateFlow("")
val alertMessageState = _alertMessageState.asStateFlow()

suspend fun showAlertMessage(message: String) {
_alertMessageState.value = message
}
}
class ChildViewModel: ParentViewModel(){
// some child view model's logic
}
interface AlertMessageDelegate {
val alertMessageState: StateFlow<String>
suspend fun showAlertMessage(message: String)
}

class ViewModelAlertMessageDelegate : AlertMessageDelegate {
private val _alertMessageState = MutableStateFlow("")
override val alertMessageState = _alertMessageState.asStateFlow()

override suspend fun showAlertMessage(message: String) {
_alertMessageState.value = message
}
}
class ExampleViewModel : ViewModel(), AlertMessageDelegate by ViewModelAlertMessageDelegate() {
fun doSomething() {
viewModelScope.launch {
showAlertMessage("Composition is great way")
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store