Ara Mkrtchyan
Ara Mkrtchyan

Reputation: 507

Android: Override viewmodel object in child fragment using Koin?

I have the following case here, I got 2 fragments:

LoginFragment : BaseAuthFragment
RegFragment : BaseAuthFragment

and corresponding viewModels:

LoginViewModel : BaseAuthViewModel
RegViewModel : BaseAuthViewModel

LoginFragment has a LoginViewModel object RegFragment has a RegViewModel object BaseAuthFragment has a BaseAuthViewModel object

I am using Koin for dependency injection so that viewModel object declaration in BaseAuthFragment is smth like this:

private val viewModel: BaseAuthViewModel by viewModel()

BaseAuthViewModel keeps common livedata observable objects for both Login && Reg fragments, like loading, error, etc..

What I am trying to achieve is that I want to observe those common Livedata objects from BaseAuthViewModel inside of BaseAuthFragment, so that I don't have to copy the code in LoginFragment && RegFragment separately.

But inside of LoginFragment && RegFragment I should already have LoginViewModel and RegViewModel, which are children of BaseAuthViewModel, so is it possible to somehow override the viewModel object type in child fragments ?

Upvotes: 0

Views: 399

Answers (1)

Varsha Kulkarni
Varsha Kulkarni

Reputation: 1574

You can define something like this:

Base class

abstract class BaseFragment : Fragment() {
    /**
     * Every fragment has to have an instance of a view model that extends from the BaseViewModel
     */
    abstract val _viewModel: BaseViewModel

    ...
}

child class

class ChildFragment : BaseFragment() {
    override val _viewModel: ChildViewModel by inject()
...
}

Upvotes: 1

Related Questions