navGraph viewModel是如何在内部工作的?

huangapple go评论75阅读模式
英文:

how does navGraph viewModel work under the hood?

问题

所以我的问题很直接。ViewModel 需要一个范围来保持存活,比如 activity 或 fragment。所以我猜测一定有一个与 navgraph 相关联的类,可以在多个 fragment 之间存活。那么这是如何实现的?

val viewModel by navGraphViewModels(R.id.my_nav_graph)
英文:

so my question is pretty straight forward. viewmodel needs a scope to stay alive. such as activity or fragment. so I guess there must be a class associated with the navgraph that survives through multiple fragments.so how is that implemented?

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

答案1

得分: 4

根据使用NavBackStackEntry文档引用目的地

从Navigation 2.2.0开始,您可以通过调用NavController.getBackStackEntry()并传递目标ID来获取导航堆栈上任何目标的NavBackStackEntry引用。

返回的NavBackStackEntry提供了目标级别的Lifecycle,**ViewModelStore**和SavedStateRegistry。这些对象在目标在后退堆栈上存在期间有效。当相关目标从后退堆栈弹出时,Lifecycle被销毁,状态不再保存,任何ViewModel对象也会被清除。

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

英文:

As per the 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.

So when you call by navGraphViewModels(), it is the NavBackStackEntry for that navigation graph that is used. As that NavBackStackEntry remains on the back stack while you're on any of the destination within that graph, that same NavBackStackEntry is returned no matter what destination in that graph you call by navGraphViewModel() on, ensuring that those multiple fragments all have a shared scope. Once you pop all of the fragments off the back stack, the navigation graph and its NavBackStackEntry are also popped, clearing out that shared state.

huangapple
  • 本文由 发表于 2020年8月9日 00:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63317725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定