android 对同一类型使用多个@Assisted

enyaitl3  于 2023-10-14  发布在  Android
关注(0)|答案(1)|浏览(105)

我在ViewModel中使用了Dagger Assisted。当我用一个相同类型的@Assisted参数创建ViewModel时,它工作得很好。但是,当有多个相同类型的@Assisted参数时,就会出现问题。
下面是我的ViewModel类:

class SampleViewModel @AssistedInject constructor(
    @Assisted val param1: Float,
    @Assisted val param2: Float,
    @Assisted val param3: Float,
) : ViewModel() {

    @AssistedFactory
    interface Factory {
        fun create(
            param1: Float,
            param2: Float,
            param3: Float
        ): SampleViewModel
    }

    companion object {
        fun provideFactory(
            assistedFactory: Factory,
            param1: Float,
            param2: Float,
            param3: Float
        ): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
            @Suppress("UNCHECKED_CAST")
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return assistedFactory.create(
                    param1,
                    param2,
                    param3
                ) as T
            }
        }
    }
    
    // .......
}

以下是Fragment:

@AndroidEntryPoint
class SampleFragment : Fragment() {

    @Inject
    lateinit var viewModelAssistedFactory: SampleViewModel.Factory

    override val viewModel: SampleViewModel by viewModels {
        SampleViewModel.provideFactory(
            viewModelAssistedFactory,
            args.param1,
            args.param2,
            args.param3
        )
    }

    // .......
}

所有参数出现的错误:

error: @AssistedInject constructor has duplicate @Assisted type: @Assisted float. Consider setting an identifier on the parameter by using @Assisted("identifier") in both the factory and @AssistedInject constructor
    float param1, @dagger.assisted.Assisted
          ^

如何处理此错误?

jhdbpxl9

jhdbpxl91#

您可以使用键指定@Assisted,如下所示:

class SampleViewModel @AssistedInject constructor(
    @Assisted("param1") val param1: Float,
    @Assisted("param2") val param2: Float,
    @Assisted("param3") val param3: Float,
) : ViewModel() {

    @AssistedFactory
    interface Factory {
        fun create(
            @Assisted("param1") param1: Float,
            @Assisted("param2") param2: Float,
            @Assisted("param3") param3: Float
        ): SampleViewModel
    }
    ...

相关问题