I have created an abstract BaseFragment class which will be extended by other concrete Fragment classes. I want to inject ViewModel in my BaseFragment using Koin. Here is my BaseFragment:
abstract class BaseFragment<out VM : BaseViewModel, DB : ViewDataBinding>(private val mViewModelClass: Class<VM>) : Fragment() {
val viewModel: VM by viewModel()
open lateinit var binding: DB
fun init(inflater: LayoutInflater, container: ViewGroup) {
binding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
}
open fun init() {}
@LayoutRes
abstract fun getLayoutRes(): Int
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
init(inflater, container!!)
init()
super.onCreateView(inflater, container, savedInstanceState)
return binding.root
}
open fun refresh() {}
}
But I am not able to do so. I am using 2.0.1 version of Koin
Something like this?
abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding>() : Fragment() {
protected abstract val viewModel: VM
@LayoutRes
protected abstract val layoutRes: Int
protected lateinit var binding: DB
fun init(inflater: LayoutInflater, container: ViewGroup) {
binding = DataBindingUtil.inflate(inflater, layoutRes, container, false)
}
open fun init() {}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
init(inflater, container!!)
init()
return binding.root
}
open fun refresh() {}
}
class SampleFragment : BaseFragment<SampleVM, FragmentSampleBinding>() {
override val viewModel by inject<SampleVM>()
override val layouRes = R.layout.fragment_sample
}
I thought to pass the ViewModel classtype to BaseFragment and inject it there. Is that not possible? As per your answer, we still need to inject the ViewModel object in the concrete fragment class.
@SAGARSURI you can see this Cannot resolve viewModel injection with delegate style declaration
@leasual that made things clear.
I close this question issue. Reopen it if needed 馃憤
Most helpful comment
@SAGARSURI you can see this Cannot resolve viewModel injection with delegate style declaration