navGraph viewModel 是如何工作的?

how does navGraph viewModel work under the hood?

所以我的问题很简单。 viewmodel 需要一个范围来保持活力。例如 activity 或片段。所以我想一定有一个 class 与 navgraph 相关联,它通过多个 fragments.so 存活下来,这是如何实现的?

val viewModel by navGraphViewModels(R.id.my_nav_graph).

根据 Reference a destination using NavBackStackEntry documentation:

Starting with Navigation 2.2.0, you can get a reference to the NavBackStackEntry for any destination on the navigation stack by calling NavController.getBackStackEntry(), passing it a destination ID.

The returned NavBackStackEntry provides a Lifecycle, a ViewModelStore, and a SavedStateRegistry at the destination level. These objects are valid for the lifetime of the destination on the back stack. When the associated destination is popped off the back stack, the Lifecycle is destroyed, the state is no longer saved, and any ViewModel objects are cleared.

因此,当您调用 by navGraphViewModels() 时,使用的是该导航图的 NavBackStackEntry。当您在该图中的任何目的地时,NavBackStackEntry 仍保留在返回堆栈中,因此无论您在该图中的哪个目的地调用 by navGraphViewModel(),都会返回相同的 NavBackStackEntry,确保这些多个片段都具有共享范围。一旦您从返回堆栈中弹出所有片段,导航图及其 NavBackStackEntry 也会弹出,从而清除该共享状态。