Issue
Hey I want to create BaseFragment class that gets viewModel by generic type:
abstract class BaseFragment<B : ViewDataBinding, VM : ViewModel> : DaggerFragment() {
val viewModel by viewModels<VM> { viewModelFactory }
...
}
// Native function
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
but getting error Cannot use 'VM' as reified type parameter. Use a class instead.
is it at all possible to achieve what I am trying to do? Maybe with other approach?
Solution
There is clearer solution:
abstract class BaseActivity<VM : BaseViewModel> : AppCompatActivity {
protected val viewModel: VM by viewModel(clazz = getViewModelClass())
private fun getViewModelClass(): KClass<VM> = (
(javaClass.genericSuperclass as ParameterizedType)
.actualTypeArguments[0] as Class<VM>
).kotlin
}
And usage:
class MainActivity : BaseActivity<MainViewModel>(R.layout.activity_main) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.onViewCreated()
}
}
Answered By - ianbelow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.