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:

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

ViewModelFactory:

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

ViewModel:

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

Fragment:

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.