我首先尝试 androidViewModel
和Hilt
DI
正如我从下面的链接中了解的那样,要使用运行时值初始化 ViewModel,我应该使用ViewModelFactory
//ViewModel
class ScoreViewModel(finalScore: Int) : ViewModel() {
// The final score
var score = finalScore
init {
Log.i("ScoreViewModel", "Final score is $finalScore")
}
}
//ViewModelFactory
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {
return ScoreViewModel(finalScore) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
//Fragment
viewModelFactory = ScoreViewModelFactory(ScoreFragmentArgs.fromBundle(arguments!!).score)
并且要使用带有刀柄的 ViewModel,我应该@ViewModelInject
按照以下链接中的说明使用
//ViewModel
class ExampleViewModel @ViewModelInject constructor(
private val repository: ExampleRepository,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
//Activity / Fragment
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
private val exampleViewModel: ExampleViewModel by viewModels()
...
}
但是怎么Hilt
用ViewModelFactory
呢?
似乎答案在@Assisted
但我不知道如何
如何告诉 hilt 我喜欢将存储库接口注入 ViewModel,同时仍然允许 ViewModelFactory 在运行时使用参数初始化 ViewModel?