我有一个应用程序,它有一个主要的活动和片段依赖于它,所以这是正常的。
现在,我的10个片段中的两个需要通信,我使用这里给出的示例
https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}
现在,如果MasterFragment和DetailFragment死了(popBackStack()都死了),视图模型的示例是否会保持活动状态,直到我完成包含这个Fragments的MainActivity?因为现在我不再需要视图模型示例了,但是根据文档所说,这个示例将从包含这些片段的Activity中保留下来
这不是我想要的片段之间的通信,因为现在该视图模型的一个新示例将与我创建的过去的示例相同,我的意思是,它将重用我使用的已经弹出的片段的示例,其中我需要额外处理删除或重置该视图模型中的所有数据,而不是获得一个新的视图模型。
它是以这种方式工作的,还是当堆栈中不再有依赖它的片段时,该示例会自动死亡?
2条答案
按热度按时间vi4fp9gy1#
现在,如果MasterFragment和DetailFragment死了(popBackStack()都死了),视图模型的示例是否会保持活动状态,直到我完成包含这个Fragments的MainActivity?
正确。虽然只有两个片段使用它,但
ViewModel
的作用域是Activity。我的意思是,它将重用我使用的已经弹出的片段的示例,其中我将需要额外处理删除或重置此视图模型中的所有数据,而不是获得一个新的视图模型。
那么你可能不应该使用
activityViewModels()
。例如,您可以将这两个片段隔离到一个嵌套的导航图中,并设置一个作用域为该图的视图模型。它是以这种方式工作的,还是当堆栈中不再有依赖它的片段时,该示例会自动死亡?
ViewModel
系统不知道什么是或不是“依赖于它”。它完全基于提供它的ViewModelStore
和theViewModelStoreOwner
。activityViewModels()
将Activity用作ViewModelStoreOwner
,因此ViewModelStore
中的视图模型与Activity绑定。3qpi33ja2#
继续@CommonsWare的回答,对于任何想要清除特定视图模型并拥有单一活动架构的人
使用诸如:
activity?.viewModelStore?.clear()
清除Activity中的所有视图模型,这很麻烦。解决方案是:为您想要共享一个视图模型的片段集创建一个嵌套图,然后将您的视图模型的范围限定为一个嵌套的导航图
Scope your viewmodel to a nested nav-graph