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

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

问题描述

因此,我正在使用新的导航组件(具有一个活动原理),并使用共享的视图模型在每个片段之间进行通信,但是,到了我有时需要清除视图模型的地步,但是我可以找不到清除它的好地方.但是,我认为我不是要自己清除它,而是应该允许该框架为我自己做,但这不是因为视图模型是共享的并且作用域为活动,但是我认为我可以将它们的作用域为一个父片段,我画了一个图来说明我要做什么.,所以当我从"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

推荐答案

好的,在父级中使用它

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天全站免登陆