简体   繁体   中英

Inject generic ViewModel Dagger Hilt Android

Hi I want to inject generic ViewModel type in my BaseActivity, how do i solve that using Dagger Hilt.

@AndroidEntryPoint
 abstract class BaseActivity<VM: BaseViewModel> : AppCompatActivity() {

@Inject
lateinit var viewModel: VM

}

Update 1

Here is the reply I was talking about from Hilt team:

So @ViewModelInject is kind of a one way thing, similar to @AndroidEntryPoint in a way. It only gets Dagger dependencies into your class. It does not add your ViewModel to the object graph as a Dagger binding. In order to access your ViewModel in a provider or somewhere else, you still need to go through the normal Android APIs of getting a view model like using a ViewModelProvider.

The reason we can't provide it into the graph is that we don't know what ViewModelStoreOwner you want to use it with.

You can find this comment here .


Original Answer

I was trying to do this days ago, and I think I read it somewhere on inte.net that it is not possible for Hilt to do this (I couldn't find the link till now).

Normally in Java we create ViewModel like this:

MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);

We need to provide ViewModelStoreOwner in ViewModelProvider constructor, and I learned that hilt cannot know which ViewModelStoreOwner you want MyViewModel to be created for.

So we will keep creating view models the old way, and in Kotlin you will stick to do it like this:

@AndroidEntryPoint
abstract class BaseActivity: AppCompatActivity() {

    private val viewModel: MyViewModel by viewModels()

}

Once I find that comment mentioning this from Hilt team, I will update the answer here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM