我在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
^
如何处理此错误?
1条答案
按热度按时间jhdbpxl91#
您可以使用键指定
@Assisted
,如下所示: