Jetpack - ViewModel

探讨了在Android开发中使用ViewModel来优化UI控制器状态管理的方法。解决了因配置改变导致的UI数据丢失问题,避免了资源浪费和潜在内存泄漏。通过实例展示了如何在活动和片段间共享数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:

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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值