Android Hilt - 两个 Fragment 之间共享 ViewModel

Pho*_*gBM 3 android dagger-hilt

我在项目中使用 Jetpack Navigation 和 Hilt,并且我想仅在两个 Fragment 之间共享 ViewModel,如下所示:

  • 片段A:使用ViewModel A
  • 在片段 A 中导航到片段 B:使用 ViewModel B
  • 在片段 B 中导航到片段 C:使用 ViewModel B 的实例
  • 如果从C回到B,再回到A那么ViewModel B将会被销毁。

如何像这样配置 ViewModel B ?

更新:我找到了一种使用 Hilt Custom Scope 的方法,但我还不知道如何实现它。

提前致谢。

Dươ*_*inh 8

您可以activityViewModels()按照宿主活动的生命周期使用 ViewModel。

class BFragment: Fragment() {
    // Using the activityViewModels() Kotlin property delegate from the
    // fragment-ktx artifact to retrieve the ViewModel in the activity scope
    private val viewModel: BViewModel by activityViewModels()
}

class CFragment : Fragment() {

    private val viewModel: CViewModel by viewModels()
    
    private val shareViewModel: BViewModel by activityViewModels()
}
Run Code Online (Sandbox Code Playgroud)

或者,如果片段 C 是 B 的子片段,您可以自定义视图模型的生命周期,如下所示:

class BFragment: Fragment() {
    // Using the viewModels() Kotlin property delegate from the fragment-ktx
    // artifact to retrieve the ViewModel
    private val viewModel: BViewModel by viewModels()
}

class CFragment: Fragment() {
    // Using the viewModels() Kotlin property delegate from the fragment-ktx
    // artifact to retrieve the ViewModel using the parent fragment's scope
    private val shareViewModel: BViewModel by viewModels({requireParentFragment()})

    private val viewModel: CViewModel by viewModels()
}
Run Code Online (Sandbox Code Playgroud)

详细信息:与片段通信