Skip to content

ViewModel reflection

Create viewModel

Version 0.5.2

reflectViewModel can create ViewModel by reflection.

Defining the base class, taking ReflectBaseActivity1 as an example.

abstract class ReflectBaseActivity1<VB : ViewBinding, VM : ViewModel> : AppCompatActivity() {

    // ViewModel
    protected val mViewModel: VM by lazy {
        reflectViewModel(this.javaClass, this)
    }

}

Making your Activity extends the ReflectBaseActivity1 , for example:

class ReflectViewModel1() : ViewModel(){
    ... // Content
}

class ReflectActivity1 : ReflectBaseActivity1<ActivityMyBinding, ReflectViewModel1>() {
    ... // Content
}

Create viewModel(Constructor with parameters)

Version 0.5.2

In order to create a ViewModel(Constructor with parameters) , you can take the following code as an example:

Defining the base class, taking ReflectBaseActivity2 as an example. And providing a function like createViewModel so that the subclass can override it to return the ViewModel instance which have parameters in constructor.

Defining the ReflectBaseActivity2:

abstract class ReflectBaseActivity2<VB : ViewBinding, VM : ViewModel> : AppCompatActivity() {

    // ViewModel
    protected val mViewModel: VM by lazy {
        reflectViewModel(this.javaClass, this) {
            return@reflectViewModel createViewModel(it)
        }
    }

    protected open fun createViewModel(modelClass: Class<out ViewModel>): ViewModel {
        return modelClass.newInstance()
    }

}

Making your Activity extends the ReflectActivity2 and override the createViewModel , for example:

class ReflectViewModel2(val parameter: String) : ViewModel(){
    ... // Content
}

class ReflectActivity2 : ReflectBaseActivity2<ActivityMyBinding, ReflectViewModel2>() {

    override fun createViewModel(modelClass: Class<out ViewModel>): MyViewModel2 {
        return MyViewModel2("parameter")
    }

}

Sample code

Sample code