Group Group Group Group Group Group Group Group Group

MVVM Android Architecture Component

Does anyone have an example that uses an interface over a ViewModel & the ViewModel Interface is provided to the fragment via the ViewModel factory instead of the concrete implementation of the view model.

If I understand correctly, you want to pass an instance of the interface from the fragment to the viewmodel through the viewmodel factory? In that case you can do something like this in Kotlin:


interface MyInterface {
    fun addNumbers(x: Int, y: Int): Int


class MyViewModelFactory(
        val iface: MyInterface,
        private val application: Application) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom( {
            return MyViewModel(iface, application) as T
        throw IllegalArgumentException("Unknown ViewModel class")


class MyViewModel(iface: MyInterface, application: Application) : AndroidViewModel(application) {
    // viewmodel implementation


val application = requireNotNull(this.activity).application
val viewModelFactory = MyViewModelFactory(object: MyInterface {
        override fun addNumbers(x: Int, y: Int): Int {
            return x + y
    }, application)

This topic was automatically closed after 166 days. New replies are no longer allowed.