Koin: How to inject viewModel in BaseFragment in Koin

Created on 27 Jun 2019  路  5Comments  路  Source: InsertKoinIO/koin

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

android question

Most helpful comment

All 5 comments

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.

@leasual that made things clear.

I close this question issue. Reopen it if needed 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guymclean picture guymclean  路  3Comments

Jeevuz picture Jeevuz  路  4Comments

luna-vulpo picture luna-vulpo  路  4Comments

hkelidari picture hkelidari  路  3Comments

AHarazim picture AHarazim  路  3Comments