背景:

The Android framework manages the lifecycles of UI controllers, such as activities and fragments.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. 

 

遇到的问题举例:

For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. 

 

传统的解决方式(例如很多题库App的处理方式,一个activity持有N多个statefragment):

 the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate()

弊端1

 but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

一个Activity holds非常多的的Fragment,每个fragment都有可能被destroy或者recreate,所以必须在上述函数中序列化保存,很麻烦不说,限制也很大,大一些的数据会出现丢失的情况。

 

弊端2

Another problem is that UI controllers frequently need to make asynchronous calls that may take some time to return. The UI controller needs to manage these calls and ensure the system cleans them up after it's destroyed to avoid potential memory leaks. This management requires a lot of maintenance, and in the case where the object is re-created for a configuration change, it's a waste of resources since the object may have to reissue calls it has already made.

 

知识描述:

1,

ViewModel可以包含LifecycleObservers,例如LiveData对象,但是不要持有view,LIfecycle或者任何(持有activity context引用)的对象。

也不要观察lifecycle-aware observables的变化,例如LiveData,如果需要一个context,可以继承AndroidViewModel,获得。

2,在屏幕旋转的时候可以保存数据而不是销毁。

3,share data between fragments

例子:

 

Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

 

和Room、LiveData组合 replace “loader”

更多相关文章

  1. Android手势操作(一)
  2. Android将应用log信息保存文件
  3. Android手势操作(三)
  4. Android(安卓)搜索框自动提示及其保存历史记录
  5. Android:使用密码技术安全地保存凭证
  6. Bitmap转为文件保存
  7. Android开发笔记: Activity
  8. Android左右滑动切换图片
  9. retrofit2持久化保存cookie

随机推荐

  1. 关于android工程中R.java不自动生成的问
  2. 解析 Android(安卓)异步消息机制,深入了解
  3. Android TextView的滑动
  4. Android之Service与IntentService的比较
  5. Android开发环境配置简介
  6. Ubuntu 10.04下Android开发环境的搭建
  7. android 线程优先级设置
  8. 用于替代 Android 自带 Dialog 和 PopupW
  9. Android从零开始-Android工程的目录结构
  10. Android核心技术——Android入门-威哥_马