简体   繁体   English

BackPress 时 ViewModel 数据丢失

[英]ViewModel Data Lost When BackPress

firstly I want to say I am sorry.首先我想说对不起。 I am newbie in MVVM.我是 MVVM 的新手。 I want to know how to retain the data in viewmodel ??我想知道如何在viewmodel中保留数据??

For example I have followed this codelab tutorial https://codelabs.developers.google.com/codelabs/android-lifecycles/#0 .例如,我遵循了这个代码实验室教程https://codelabs.developers.google.com/codelabs/android-lifecycles/#0

  1. I try to kill the apps then go back into the apps but the data is not saved .Why?我尝试杀死应用程序,然后返回应用程序,但未保存数据。为什么?

  2. I tried to make new activity by intent it.我试图通过意图进行新的活动。 I ln new activity I implement the same code as statelifecyle.我在新活动中实现了与 statelifecyle 相同的代码。 But why when I backpressed and try to enter back the newactivity the data is not saved ?但是为什么当我回退并尝试输入新活动时,数据没有保存?

To answer your questions:回答您的问题:

  1. Data in ViewModel is only persisted throughout the lifecycle of your activity. ViewModel 中的数据仅在您的活动的整个生命周期中保留。 So if your app dies, your data is not saved.因此,如果您的应用程序停止运行,您的数据将不会被保存。 If you want it to persist, consider integrating an off-line data persistence library like Room or you can also use SharedPreferences depending on your use case.如果你想让它持久化,可以考虑集成一个离线数据持久化库,比如Room或者你也可以根据你的用例使用SharedPreferences

  2. According to this post: Android LiveData - how to reuse the same ViewModel on different activities?根据这篇文章: Android LiveData - 如何在不同的活动上重用相同的 ViewModel?

When you call ViewModelProviders.of(this), you actually create/retain a ViewModelStore which is bound to this, so different Activities have different ViewModelStore and each ViewModelStore creates a different instance of a ViewModel using a given factory, so you can not have the same instance of a ViewModel in different ViewModelStores当您调用 ViewModelProviders.of(this) 时,您实际上创建/保留了一个绑定到此的 ViewModelStore,因此不同的活动具有不同的 ViewModelStore,并且每个 ViewModelStore 使用给定的工厂创建一个不同的 ViewModel 实例,因此您不能拥有不同 ViewModelStores 中的同一个 ViewModel 实例

In other words, different activities cannot share a single ViewModel.换句话说,不同的 Activity 不能共享一个 ViewModel。 So if you want to switch pages while retaining data in your ViewModel, consider using fragments inside your activity instead.因此,如果您想在切换页面的同时保留 ViewModel 中的数据,请考虑在您的 Activity 中使用片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM