我已经针对我的 ViewModels 生命周期中的问题修改了@slodge 的一个示例。
我对 N26 做了一点修改: https ://github.com/csteeg/NPlus1DaysOfMvvmCross/tree/viewmodeldisposesample/N-26-Fraggle
这个分支使用 mvxmessenger 插件能够告诉你哪里出了问题。代码不是很漂亮,但表明你 wat 不正确。您可以看到 ID = 0 的 SubViewModel 如何继续接收消息,即使它的视图早已不复存在。还有(在某些时候) HomeViewModel 如何停止接收消息。
重现步骤(包括调试输出的清理版本):
启动应用程序
HomeViewModel:Warning:HomeViewModel 0 received: Created HomeViewModel0
点击按钮“1”
HomeViewModel:Warning:HomeViewModel 0 received: Created SubViewModel0
SubViewModel:Warning:SubViewModel 0 received: Created SubViewModel0
HomeViewModel:Warning:HomeViewModel 0 received: Created FirstViewModel0
SubViewModel:Warning:SubViewModel 0 received: Created FirstViewModel0
FirstViewModel:Warning:FirstViewModel 0 received: Created FirstViewModel0
点击返回
HomeViewModel:Warning:HomeViewModel 0 received: Destroyed FirstView for viewmodel 0
SubViewModel:Warning:SubViewModel 0 received: Destroyed FirstView for viewmodel 0
FirstViewModel:Warning:FirstViewModel 0 received: Destroyed FirstView for viewmodel 0
HomeViewModel:Warning:HomeViewModel 0 received: Destroyed SubFrag for viewmodel 0
SubViewModel:Warning:SubViewModel 0 received: Destroyed SubFrag for viewmodel 0
FirstViewModel:Warning:FirstViewModel 0 received: Destroyed SubFrag for viewmodel 0
HomeViewModel:Warning:HomeViewModel 0 received: Destroyed DubFrag for viewmodel 0
SubViewModel:Warning:SubViewModel 0 received: Destroyed DubFrag for viewmodel 0
FirstViewModel:Warning:FirstViewModel 0 received: Destroyed DubFrag for viewmodel 0
您可以在这里看到视图被破坏,我希望视图模型与它们一起使用
再次单击按钮“1”
HomeViewModel:Warning:HomeViewModel 0 received: Created SubViewModel1
SubViewModel:Warning:SubViewModel 0 received: Created SubViewModel1
FirstViewModel:Warning:FirstViewModel 0 received: Created SubViewModel1
SubViewModel:Warning:SubViewModel 1 received: Created SubViewModel1
HomeViewModel:Warning:HomeViewModel 0 received: Created FirstViewModel1
SubViewModel:Warning:SubViewModel 0 received: Created FirstViewModel1
FirstViewModel:Warning:FirstViewModel 0 received: Created FirstViewModel1
SubViewModel:Warning:SubViewModel 1 received: Created FirstViewModel1
FirstViewModel:Warning:FirstViewModel 1 received: Created FirstViewModel1
你看,subviewmodel 0 仍在接收消息。我可以以某种方式告诉它应该停止向未附加的视图模型发送消息吗?或者视图模型是否知道未附加
现在,当您继续重复这些步骤相当长的一段时间,比如在模拟器中 15 次时,一些视图模型将停止接收消息(我猜它们是垃圾收集的)。奇怪的是,其中一个视图是HomeViewModel!HomeView 永远不会被破坏,但是 homeviewmdoel 会停止接收消息,因此如果您的应用程序需要,nog 能够相应地更新视图