当前位置:网站首页>Jetpack之LiveData扩展MediatorLiveData
Jetpack之LiveData扩展MediatorLiveData
2022-07-02 03:38:00 【Jason_Lee155】
LiveData的使用前面已经说过:
Android Jetpack组件之 LiveData使用-源码
但是Android库里也有一些扩展类,比如 MediatorLiveData 需要介绍下。
假设有一个需求:在ExitText中输入文字的同时,显示文字个数。当然可以用EditTextChangeListener,也可以只用一个LiveData监听输入String也可以得到length,但是这里只是举例嘛。
class MainViewModel : ViewModel() {
val message: MutableLiveData<String> = MutableLiveData()
val count: MediatorLiveData<Int> = MediatorLiveData()
init {
count.value = 0
count.addSource(message) {
val cnt = message.value?.length ?: 0
count.postValue(cnt)
}
}
fun postMessage(message: String) {
this.message.postValue(message)
}
}MediatorLiveDarta的作用,顾名思义可以作为中间人的角色监听其他LiveData。这里可以在EditText的回调里通过postMessage更新message,count通过addSource监听message的变化后更新输入长度。

用Java版本看看:
例如:从getNameFromServer()取的值是"alan",而MediatorLiveData做了转化后成了"alan gong"。
public class MyViewModel extends ViewModel {
private MutableLiveData<String> liveEvent;
private MediatorLiveData<String> testLiveData;
public MyViewModel() {
testLiveData = new MediatorLiveData<>();
testLiveData.addSource(liveEvent, new Observer<String>() {
@Override
public void onChanged(String s) {
testLiveData.postValue(s + " gong");
}
});
getNameFromServer();
}
public MediatorLiveData<String> getTestLiveData() {
return testLiveData;
}
private void getNameFromServer() {
if (liveEvent == null) {
liveEvent = new MutableLiveData<>();
}
liveEvent.setValue("alan");
}
}
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
setContentView(binding.getRoot());
ViewModelProvider provider = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory());
MyViewModel myViewModel = provider.get(MyViewModel.class);
binding.setViewModel(myViewModel);
myViewModel.getTestLiveData().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
textView.setText(s);
}
});
}
}至于原理,相信会使用LiveData的都觉得没什么,studio里点这个类进入源码看看就行了。
边栏推荐
- Influence of air resistance on the trajectory of table tennis
- "Analysis of 43 cases of MATLAB neural network": Chapter 42 parallel operation and neural network - parallel neural network operation based on cpu/gpu
- js生成随机数
- 《MATLAB 神經網絡43個案例分析》:第42章 並行運算與神經網絡——基於CPU/GPU的並行神經網絡運算
- FFMpeg AVFrame 的概念.
- Failed to upgrade schema, error: “file does not exist
- Pointer array & array pointer
- JS generate random numbers
- High performance and low power cortex-a53 core board | i.mx8m Mini
- [punch in] flip the string (simple)
猜你喜欢
![[yolo3d]: real time detection of end-to-end 3D point cloud input](/img/5e/f17960d302f663db75ad82ae0fd70f.jpg)
[yolo3d]: real time detection of end-to-end 3D point cloud input

潘多拉 IOT 开发板学习(RT-Thread)—— 实验1 LED 闪烁实验(学习笔记)

Comment élaborer une stratégie nuageuse à l'ère des nuages mixtes
![[C Advanced] brother Peng takes you to play with strings and memory functions](/img/95/ab1bb0b3fa0b99e32233a5ca5d42a4.jpg)
[C Advanced] brother Peng takes you to play with strings and memory functions

Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud

Basic operations of MySQL database (based on tables)

一天上手Aurora 8B/10B IP核(5)----从Framing接口的官方例程学起

How to do medium and long-term stocks, and what are the medium and long-term stock trading skills?

Getting started with MQ

蓝桥杯单片机省赛第七届
随机推荐
VS2010 plug-in nuget
What do you know about stock selling skills and principles
近段时间天气暴热,所以采集北上广深去年天气数据,制作可视化图看下
Global and Chinese markets for ultrasonic probe disinfection systems 2022-2028: Research Report on technology, participants, trends, market size and share
Kotlin basic learning 16
Basic operations of MySQL database (based on tables)
Global and Chinese market of autotransfusion bags 2022-2028: Research Report on technology, participants, trends, market size and share
微信小程序中 在xwml 中使用外部引入的 js进行判断计算
跳出舒适区,5年点工转型自动化测试工程师,我只用了3个月时间
High performance and low power cortex-a53 core board | i.mx8m Mini
Kotlin基础学习 15
初识string+简单用法(二)
Retrofit's callback hell is really vulnerable in kotlin synergy mode
[database]jdbc
Global and Chinese market of X-ray detectors 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL advanced (Advanced) SQL statement (II)
Xlwings drawing
一文彻底理解评分卡开发中——Y的确定(Vintage分析、滚动率分析等)
蓝桥杯单片机第六届温度记录器
leetcode-1380. Lucky number in matrix