I am trying to inject the ViewModel into the adapter. It works fine while injecting into Fragment.
ViewModel:
class HomeViewModel @ViewModelInject constructor(
): ViewModel()
Fragment:
@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>(
R.layout.fragment_home
) {
private val viewModel: HomeViewModel by viewModels()
There is no problem so far. But problems arise when I try to inject into the adapter.
class HomeListAdapter @Inject constructor(
): BaseListAdapter<Users>(
itemsSame = { old, new -> old.username == new.username },
contentsSame = { old, new -> old == new }
) {
private val viewModel: HomeViewModel by viewModels() //viewModels() unresolved reference
UPDATE:
If I try to use constructor injection or field injection I get the following error:
error: [Dagger/MissingBinding] ***.home.HomeViewModel cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract static class ApplicationC implements App_GeneratedInjector,
^
***.home.HomeViewModel is injected at
***.home.adapter.HomeListAdapter.viewModel
***.home.adapter.HomeListAdapter is injected at
***.home.HomeFragment.viewAdapter
***.home.HomeFragment is injected at
***.home.HomeFragment_GeneratedInjector.injectHomeFragment(***.home.HomeFragment) [***.App_HiltComponents.ApplicationC → ***.App_HiltComponents.ActivityRetainedC → ***.App_HiltComponents.ActivityC → ***.App_HiltComponents.FragmentC]
Adapter:
class HomeListAdapter @Inject constructor(
): BaseListAdapter<Users>(
itemsSame = { old, new -> old.username == new.username },
contentsSame = { old, new -> old == new }
) {
@Inject lateinit var viewModel: HomeViewModel;
Generally, you should not inject ViewModel into Adapter, because Adapter is a part of presentation layer and an Android-specific thing. ViewModel is something independent on Android in general, though ViewModel from AAC is tied to it.
You should get your data in ViewModel and pass it to Fragment via LiveData, and then populate your Adapter from within Fragment.
by viewModels() is not defined in Adapter since it is an extension function of Fragment and could be used only within Fragment. So, move your ViewModel away from Adapter back to Fragment. That will also fix your compilation error since Hilt doesn't inject into Adapters.