Определите ViewModel как реферат в классе BaseFragment и установите значение при расширении вашего BaseFragment.
abstract class BaseFragment<Binding : ViewDataBinding, ViewModel : BaseViewModel> : Fragment(){
protected var bindingObject: Binding? = null
protected abstract val mViewModel: ViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
bindingObject = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false)
return bindingObject?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
performDataBinding()
}
@LayoutRes
abstract fun getLayoutResId(): Int
private fun performDataBinding() {
bindingObject?.setLifecycleOwner(this)
bindingObject?.setVariable(BR.viewModel, mViewModel)
bindingObject?.executePendingBindings()
}
}
И в вашем фрагменте
class FragmentNew : BaseFragment<FragmentNewBinding, FragmentNewVM>() {
// Here is the your viewmodel imlementation. Thus when you create fragment it's by default override method
override val mViewModel: FragmentNewVM by viewModel()
override fun getLayoutResId(): Int = [fragment layout id like "R.layout.fragment_new"]
}