我遵循 Google 建议的 one-single-activity 应用程序模式,因此如果我想在 Fragments
之间共享数据,我必须共享一个 ViewModel
其所有者必须是父 Activity
。 所以,问题就变成了,因为我只想在两个 fragment 之间共享数据,而与其他 fragment 无关。
假设我有 MainFragment
、CreateItemFragment
和 ScanDetailFragment
。因此,从第一个导航到 CreateItemFragment 时,每当我按下按钮时,我都会导航到 ScanDetailFragment 以扫描条形码,因此,通过 ViewModel 中的 LiveData
对象,我可以获得扫描的ScandDetailFragment 完成后,值返回到 CreateItemFragment。当我决定取消项目的创建时,问题就出现了:我回到“MainFragment”,因为 ViewModel 的所有者是 Activity 的生命周期,一旦我再次进入 CreateItemFragment,之前扫描的值仍然存在。
有重置 ViewModel 的想法吗?
最佳答案
but, aren't Viewmodels also aimed to share data between different views?
没有。每个 View 模型应该负责一个 View 。 “共享 View 模型”模式适用于您有一个大 View (即 Activity )的情况,该 View 具有多个需要共享数据/状态的 subview (即 fragment ),例如 the master / detail example in the documentation .当您需要在 subview 之间进行实时更新时,这对这些情况很方便。
在您的情况下,您在 fragment 之间导航,因此应该通过转换传递数据。这意味着 passing arguments along when starting new fragments和 registering for results when they complete their task .
然后您的每个 fragment 都是隔离的、自包含的、更容易测试的,并且您最终不会得到一个做所有事情™ 的上帝 View 模型,并在您尝试跳过篮球会计时变成一团糟对于它可能处于的每个状态。
关于android - 重置/清除 View 模型或实时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67824325/