如果我使用 SharedViewModel 传递数据,我必须在片段中使用多少个视图模型?

how many view models I have to use in my fragment if I use SharedViewModel to pass data?

我正在使用导航组件,我需要将数据从片段 B 传回片段 A。我已阅读 here that I need to use SharedViewModel

例如,我有一个显示餐馆列表的 RestaurantListFragment。为了处理这个片段的网络和业务逻辑,我制作了 RestaurantListViewModel .

我的第二个片段是RestaurantDetailFragment。为了处理这个片段中的一些动作和业务逻辑,我创建了 RestaurantDetailViewModel .

现在需要把RestaurantDetailFragment的数据传回RestaurantListFragment,据说需要用到SharedViewModel。但现在我很困惑。

如果我使用 SharedViewModel 传递数据,那么我将在一个片段中有 2 个视图模型?在 RestaurantDetailFragment 中,我将有 RestaurantDetailViewModelXSharedViewModel,在 RestaurantDetailFragment 中,我将有 RestaurantListViewModelXSharedViewModel

所以在 SharedViewModel 中它只包含需要传递回前一个片段的数据?

或者我只需要制作一个视图模型 (SharedViewModel) 来为我的两个片段提供服务? (我不再需要创建 RestaurantDetailViewModelRestaurantListViewModel)。我很困惑。

两种方法都有效:

  1. 您可以仅将 SharedViewModel 用于 RestaurantDetailFragmentRestaurantListFragment 之间共享的数据和方法,并保留仅 [=12] 所需的逻辑=] 但不适用于 RestaurantListViewModel 内的 RestaurantDetailFragment,反之亦然。

  2. 无论如何,您也可以将 RestaurantDetailViewModelRestaurantListViewModel 的所有逻辑放在 SharedViewModel 中,并摆脱其他 2 个 ViewModel。虽然这不会引发任何错误,但它违反了 separation of concerns.

You have to create only one View Model only to share or reuse the data between 2 fragments. The concept behind the SharedViewModel is that It will create one object and store the result in LiveData of View Model and will be reused again at different fragment within one Activity Life Cycle attached to it.

如果需要

,您可以参考此Github Project表格