如何使用 Hilt 将 safe-args 参数注入视图模型?

How to use Hilt to inject a safe-args argument into a viewmodel?

我找到了一个类似的问题here. At the time of writing this question there is only this answer avaliable,对我没有任何帮助,我相信对提问者也有帮助。

我检查了答案中链接的回购协议,它通过在视图模型中创建一个 init 方法并在 Activity/Fragment 中调用它来“解决”问题。

由于已经注入了viewmodel,这个方案对我来说似乎不太理想,我想知道在使用hilt时是否还有其他选择。

根据 this comment and the release of AndroidX Hilt 1.0.0-alpha03, Hilt has supported ViewModels that take a SavedStateHandle 作为参数(与其他注入参数一起)。

SavedStateHandle 会自动填充传递给您的片段的参数(即,您从 requireArguments() 获得的相同参数以及 Safe 读取的相同参数参数).

因此,在您的 ViewModel 的构造函数中,您可以立即从 SavedStateHandle 访问这些参数,而无需手动将参数传递给您的 ViewModel。

@HiltViewModel
class MainViewModel @Inject constructor(
    val userDataManager: UserDataManager,
    savedStateHandle: SavedStateHandle
) : ViewModel() {
    init {
        // Use the same argName as in your navigation graph
        val yourArgument: String = savedStateHandle["argName"]
        // Now use that argument to load your data, etc.
    }
}

feature request for Safe Args integration with SavedStateHandle is already fixed 并将成为即将发布的 Navigation 2.4.0-alpha01 版本的一部分。发布后,您将能够执行 MainFragmentArgs.fromSavedStateHandle(savedStateHandle) 之类的操作来获得与您当前能够从 ViewModel 中的 by navArgs() 获得的相同的 Args class。