当前位置:网站首页>Android -- jetpack: the difference between livedata setValue and postvalue
Android -- jetpack: the difference between livedata setValue and postvalue
2022-07-07 15:36:00 【Liang and Android】
The content of the article comes from :https://blog.csdn.net/catzifeng/article/details/103931517
Andriod — JetPack : First time to know JetPack
Andriod — JetPack :LifeCycle The birth of
Andriod — JetPack :ViewModel The birth of
Andriod — JetPack :BaseObservable And ObservableField Two way binding
Andriod — JetPack :DataBinding + LiveData +ViewModel Simple example
Andriod — JetPack :Room Additions and deletions
Andriod — JetPack :Room + ViewModel + LiveData Add, delete, change and check the examples
Andriod — JetPack :LiveData setValue and postValue The difference between
Usually we use LiveData When , When data needs to be updated ,LiveData There are two ways to update data :
- setValue(T value)
- postValue(T value)
So what's the difference between the two ways ?
Conclusion
setValue() Can only be called in main thread ,postValue() Can be invoked in any thread. .
setValue()
Let's not rush to look at the source code , First, let's see how the official introduces this method .
/** * Sets the value. If there are active observers, the value will be dispatched to them. * <p> * This method must be called from the main thread. If you need set a value from a background * thread, you can use {@link #postValue(Object)} * * @param value The new value */
@MainThread
protected void setValue(T value)
The notes above are very clear :
This method must be invoked in the main thread. , If you need to set it in the background thread value, Please move #postValue(Object)
What's more, they used one @MainThread The notes of remind you , Next, look at the source code :
protected void setValue(T value) {
assertMainThread("setValue"); //1
mVersion++; //2
mData = value; //3
dispatchingValue(null); //4
}
private static void assertMainThread(String methodName) {
if (!ArchTaskExecutor.getInstance().isMainThread()) {
throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
+ " thread");
}
}
First call assertMainThread() Method to determine whether the current thread is the main thread ( Here he passed a ArchTaskExecutor Singleton class ), If it's not the main thread , Throw exceptions directly to remind programmers .
If the method is invoked in the main thread , Add one by yourself version, It is clear that the value has changed .
Then save the new value .
to update value( This method cannot be dragged down , Pull it down to LiveData Source code analysis of ).
postValue
Let's continue to take a look at the official right postValue() Introduction to :
/** * Posts a task to a main thread to set the given value. So if you have a following code * executed in the main thread: * <pre class="prettyprint"> * liveData.postValue("a"); * liveData.setValue("b"); * </pre> * The value "b" would be set at first and later the main thread would override it with * the value "a". * <p> * If you called this method multiple times before a main thread executed a posted task, only * the last value would be dispatched. * * @param value The new value */
protected void postValue(T value)
Which translates as :
Through the mission (Runnable) Update data in the main thread .
If... Is called at the same time .postValue(“a”) and .setValue(“b”), It must be worth b By value a Cover .
If you call more than once .postValue(), Only the last value can be distributed (onChanged() Called ).
Look at the detailed source code :
protected void postValue(T value) {
boolean postTask; //1
synchronized (mDataLock) {
//2
postTask = mPendingData == NOT_SET; //3
mPendingData = value; //3
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); //4
}
Define a postTask Boolean value , Determine whether to update .
Add a synchrolock , Because there may be multiple child threads calling at the same time .postValue() The situation of .
By judging whether the updated value has changed postTask assignment , And will value Assign a value to mPendingData(mPendingData == NOT_SET The first time must be back true, Then they all return false, Then it will be called immediately before the value is updated mPendingData=NOT_SET, That's why multiple calls postValue() Reason why only the last value is valid ).
adopt ArchTaskExecutor updated , Pass method and parameter name , We can guess what this step has done :ArchTaskExecutor Will a Runnable Object to execute in the main thread , that mPostValueRunnable The execution environment must be the main thread , Let's take a look at mPostValueRunnable What has been done .
Because now the thread has switched to the main thread , So he just called setValue()
Last
There are several times in the text ArchTaskExecutor This thing , This class is actually postValue The key to switch to the main thread update is that its specific source code implementation is very simple , Directly used Handler The mechanism of .
边栏推荐
- [quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)
- Unity's ASE realizes cartoon flame
- CTFshow,信息搜集:web14
- @ComponentScan
- How to release NFT in batches in opensea (rinkeby test network)
- [quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
- Niuke real problem programming - Day10
- Connecting FTP server tutorial
- Ctfshow, information collection: Web3
- Unity's ASE achieves full screen sand blowing effect
猜你喜欢
![[quick start of Digital IC Verification] 23. AHB sramc of SystemVerilog project practice (3) (basic points of AHB protocol)](/img/e9/9e32e38e12e1fa71732c52b8ee0ab0.png)
[quick start of Digital IC Verification] 23. AHB sramc of SystemVerilog project practice (3) (basic points of AHB protocol)

【數字IC驗證快速入門】20、SystemVerilog學習之基本語法7(覆蓋率驅動...內含實踐練習)

从 1.5 开始搭建一个微服务框架链路追踪 traceId
使用Scrapy框架爬取网页并保存到Mysql的实现
![[server data recovery] data recovery case of raid failure of a Dell server](/img/5d/03bc8dcc6e554273b34a78c49a9eaf.jpg)
[server data recovery] data recovery case of raid failure of a Dell server

The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service

CTFshow,信息搜集:web9

简述keepalived工作原理

【深度学习】图像超分实验:SRCNN/FSRCNN

#HPDC智能基座人才发展峰会随笔
随机推荐
[quick start of Digital IC Verification] 23. AHB sramc of SystemVerilog project practice (3) (basic points of AHB protocol)
Summer safety is very important! Emergency safety education enters kindergarten
[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
【數字IC驗證快速入門】20、SystemVerilog學習之基本語法7(覆蓋率驅動...內含實踐練習)
【兰州大学】考研初试复试资料分享
Novel Slot Detection: A Benchmark for Discovering Unknown Slot Types in the Dialogue System
暑期安全很重要!应急安全教育走进幼儿园
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
Niuke real problem programming - Day12
Starting from 1.5, build a microservice framework link tracking traceid
Ctfshow, information collection: web9
Compile advanced notes
"Baidu Cup" CTF competition 2017 February, web:include
Pat grade a 1103 integer factorizatio
Excerpted words
全日制研究生和非全日制研究生的区别!
The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
PAT 甲级 1103 Integer Factorizatio
简述keepalived工作原理
[quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)