使用 Hilt 进行依赖注入时如何将运行时参数传递给 ViewModel 的构造函数? [英] How to pass runtime parameters to a ViewModel's constructor when using Hilt for dependency injection?

查看:100
本文介绍了使用 Hilt 进行依赖注入时如何将运行时参数传递给 ViewModel 的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在将 Hilt 用于 DI 时如何将运行时参数传递给 ViewModel 的构造函数?在使用 Hilt 之前,我有一个如下所示的 ViewModel:

I'm wondering how to pass runtime parameters to a ViewModel's constructor while using Hilt for DI? Prior to using Hilt, I have a ViewModel that looks like this:

class ItemViewModel(private val itemId: Long) : ViewModel() {
    private val repo = ItemRepository(itemId) 
}

class ItemViewModelFactory(private val itemId: Long) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(ItemViewModel::class.java)) {
        return ItemViewModel(itemId) as T
    }
    throw IllegalArgumentException("Unknown ViewModel class")
}

我在我的片段中创建了上面的 ViewModel,如下所示:

I create the above ViewModel in my fragment like this:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    val args: ItemScreenFragmentArgs by navArgs()
    val itemId = args.itemId

    //Create the view model factory
    val viewModelFactory = ItemViewModelFactory(application, itemId)

    // Get a reference to the ViewModel associated with this fragment.
    val itemViewModel = ViewModelProvider(this, viewModelFactory).get(ItemViewModel::class.java)
}

如果我的 ItemViewModel 构造函数没有 itemId 参数,则使用 Hilt 的 ViewModel 和 Fragment 将如下所示:

If my ItemViewModel constructor didn't have the itemId parameter, my ViewModel and Fragment using Hilt would look like this:

class ItemViewModel
@ViewModelInject
constructor(private val repo: ItemRepository) : ViewModel() { }

@AndroidEntryPoint
class ItemFragment : Fragment() {
    private val itemViewModel: ItemViewModel by viewModels ()
}

我想弄清楚如何将我从 ItemFragment 的 NavArgs 获得的 itemId 传递给 ItemViewModel 的构造函数?有没有办法用 Hilt 做到这一点?

I'm trying to figure out how to pass the itemId that I get from the ItemFragment's NavArgs to the ItemViewModel's constructor? Is there a way to do this with Hilt?

推荐答案

对于希望在使用 Dagger Hilt 时将运行时参数传递给 ViewModel 的其他人,我是这样做的:

For anyone else looking to pass runtime parameters to a ViewModel while using Dagger Hilt, this is how I did it:

我遵循了这个例子中的代码,它使用了AssistedInject 库.

I followed the code from this example which uses the AssistedInject library.

我的代码现在如下所示:

My code now looks as follows:

class ItemViewModel
@AssistedInject
constructor(private val repo: ItemRepository, @Assisted private val itemId: Long) : ViewModel() {
    init {
        repo.itemId = itemId
    }

    @AssistedInject.Factory
    interface AssistedFactory {
        fun create(itemId: Long): ItemViewModel
    }

    companion object {
        fun provideFactory(
            assistedFactory: AssistedFactory,
            itemId: Long
        ): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                return assistedFactory.create(itemId) as T
            }
        }
    }
}

@InstallIn(FragmentComponent::class)
@AssistedModule
@Module
interface AssistedInjectModule {}

@AndroidEntryPoint
class ItemFragment : Fragment() {
    private val args: ItemScreenFragmentArgs by navArgs()      
    @Inject lateinit var itemViewModelAssistedFactory: ItemViewModel.AssistedFactory        
    private val itemViewModel: ItemViewModel by viewModels {
            ItemViewModel.provideFactory(itemViewModelAssistedFactory, args.itemId)
    }    
}

这篇关于使用 Hilt 进行依赖注入时如何将运行时参数传递给 ViewModel 的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆