一、前言
为了解决Android-App开发以来一直存在的架构设计混乱的问题,谷歌推出了Jetpack-MVVM的全家桶解决方案。作为整个解决方案的核心-LiveData,以其生命周期安全,内存安全等优点,甚至有逐步取代EventBus,RxJava作为Android端状态分发组件的趋势。
官网商城app团队在深度使用LiveData的过程中,也遇到了一些困难,尤其是在LiveData的观察者使用上踩到了不少坑,我们把这些经验在这里做一次总结与分享。
二、Observer到底可以接收多少次回调
2.1 为什么最多收到2个通知
这是一个典型的案例,在调试消息总线的场景时,我们通常会在消息的接收者那里打印一些log日志方便我们定位问题,然而日志的打印有时候也会给我们的问题定位带来一定的迷惑性,可以看下面的例子。
我们首先定义一个极简的ViewModel:
public class TestViewModel extends ViewModel {
private MutableLiveData<String> currentName;
public MutableLiveData<String> getCurrentName() {
if (currentName == null) {
currentName = new MutableLiveData<String>();
}
return currentName;
}
}
然后看下我们的activity代码;
public class JavaTestLiveDataActivity extends AppCompatActivity {
private TestViewModel model;
private String test="12345";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_test_live_data);
model = new ViewModelProvider(this).get(TestViewModel.class);
test3();
model.getCurrentName().setValue("3");
}
private void test3() {
for (int i = 0; i < 10; i++) {
model.getCurrentName().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Log.v("ttt", "s:" + s);
}
});
}
}
}
大家可以想一下,这段程序运行的结果会是多少?我们创建了一个Livedata,然后对这个Livedata Observe了10次,每次都是new出不同的Observer对象,看上去我们对一个数据源做了10个观察者的绑定。当我们修改这个数据源的时候,我们理应有10条通知。运行一下看看执行结果:
2021-11-21 15:20:07.662 27500-27500/com.smart.myapplication V/ttt: s:3
2021-11-21 15:20:07.662 27500-27500/com.smart.myapplication V/ttt: s:3
奇怪,为什么我明明注册了10个观察者,但是只收到了2个回调通知?换种写法试试?
我们在Log的代码里增加一部分内容比如打印下hashCode再看下执行结果:
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:217112568
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:144514257
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:72557366
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:233087543
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:22021028
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:84260109
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:94780610
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:240593619
2021-11-21 15:22:59.377 27912-27912/com.smart.myapplication V/ttt: s:3 hashCode:207336976
2021-11-21 15:22

本文深入探讨了Android LiveData组件的使用技巧及常见陷阱,包括观察者回调次数异常、接收观察前消息等问题,并提供了多种解决方案。
最低0.47元/天 解锁文章
792

被折叠的 条评论
为什么被折叠?



