如何将视图模型范围限定为父片段? [英] How to scope a view model to a parent fragment?

查看:31
本文介绍了如何将视图模型范围限定为父片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用新的导航组件(具有一个活动原则)并使用共享视图模型在每个片段之间进行通信,但是,我已经到了有时需要清除视图模型的地步,但我可以找不到清理它的好地方.但是 tbh 我认为与其试图自己清除它,我真的应该允许框架为我做这件事,但这不是因为视图模型是共享的并限定于活动,但我认为我可以将它们限定为一个父片段,我画了一张图来说明我想要做什么. 所以我只想在我当前从Child 1 Child a"导航回来时清除 2 个视图模型视图模型永远不会被清除,试图通过在片段中调用this"来获取当前的视图模型,而在孩子中的 getParentFragment 不起作用,谁能提供一个例子?

So I'm using the new navigation component (with the one activity principle) and communicating between each fragment using shared view models, however, I've come to a point where I sometimes need to clear the view model but I can't find a good place to clear it. But tbh I think rather than trying to clear it myself, I should really be allowing the framework to do it for me, but it doesn't because the view models are shared and scoped to the activity, but I think I can scope them to a parent fragment, I made a drawing to illustrate what I'm trying to do. so I only want to clear the 2 view models when I navigate back from "Child 1 Child a" currently the view models are never cleared, trying to get the view model currently by calling 'this' in the fragment and getParentFragment in the child doesn't work, can anyone provide an example?

编辑

看起来我已经在做类似的事情,但在我的情况下不起作用,所以我将添加一些代码,这是我如何访问父片段中的第一个视图模型

It looks like I was already doing something similar but it's not working in my case so I will add some code, here is how I access the first view model in the parent fragment

model = ViewModelProviders.of(this).get(RequestViewModel.class);

然后在子片段中,我正在这样做

and then in the child fragment, I'm doing this

requestViewModel = ViewModelProviders.of(getParentFragment()).get(RequestViewModel.class);

但它并没有在他们之间保留数据,他们都附加了观察者

but it's not keeping the data between them, they both have observers attached

推荐答案

好的,所以在父级中使用这个

Ok so using this in the parent

model = ViewModelProviders.of(this).get(RequestViewModel.class);

这在孩子身上

requestViewModel = ViewModelProviders.of(getParentFragment()).get(RequestViewModel.class);

给了我不同的哈希码但相同的 ID,这似乎是因为导航组件,如果我将它们都更改为 getParentFragment 那么它就可以工作,所以我认为该组件正在替换片段而不是在此处添加它们,非常感谢致@WadeWilson 和@JeelVankhede

were giving me different hashcodes but the same IDs and it seems to be because of the navigation component, if i change them both to getParentFragment then it works, so i think the component is replacing fragments instead of adding them here, many thanks to @WadeWilson and @JeelVankhede

这篇关于如何将视图模型范围限定为父片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆