Jetpack - ViewModel

背景:

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”

Jetpack - ViewModel_第1张图片

你可能感兴趣的:(android,技术,code)