当前位置:网站首页>2.7 overview of livedata knowledge points
2.7 overview of livedata knowledge points
2022-07-03 12:15:00 【schr03p】
One 、 Concept
LiveData Is an observable data holding class . With life cycle (Activity/Fragment/Service) Perceptual ( Make sure active Accept in status data to update ).
background original text

Android In development MVX Development architecture design , The perception of life cycle is important for Controller/Presenter/ViewModel It's not natural to know . Data resources and leakage .

2018 year google Of AAC(Android Architecture Components). A combination Jetpack Component library , bring ViewModel Life cycle awareness . At the same time, it also has the ability to perceive data (LiveData)

understand LiveData

differ
rxjavaObservation mode , Only the notification is inactiveState observer .Once the observer replies
Resumestate , You will receive the latest data ( Cut both ways , Special scenes )
Two 、 Use LiveData
LiveData Abstract class
MutableLiveData
// Make a statement liveData
val liveA = mutableLiveData<String>()
// Assign values when needed
liveA.value = "some value of liveA"
//
// stay UI in , Observe , stay active The state can perceive changes
val liveAObserver = Observer<String>{
value?.let{
//do something
}
}
liveA.observe(vivewLifeCycleOwner,liveAObserver)Transformations.map
// The sources of data are diverse , Assigned to UI Need to transform
liveA.map{
// Conversion rules
}
==liveData The data of , No notice inActive The observer refreshes the data , But when observer recovery Resume Of active after , Will also get the latest data==

MediatorLiveData
Intermediary , medium , Will be multiple liveData The data of , Merge into one LiveData

mediator Of liveData Can monitor A,B Changes in the two data sources , adopt addSource after , And respond to A/B The change of , Turn into mediator The change of .
If inactive Next ,A,B All change , be resume after , Only accept the latest changes
SwitchMap
Used for data source conversion , Switching and control of multiple data sources
coordination mediator Of liveData Use , According to the condition , Select data source
btn_change1_live.setOnClickListener {
liveOne.value = "one:${System.currentTimeMillis().toString().takeLast(6)}"
}
btn_change2_live.setOnClickListener {
liveTwo.value = "two:${System.currentTimeMillis().toString().takeLast(6)}"
}
// Intermediary
mediatorLive.addSource(liveOne) {
Log.d("LiveActivity", "LiveActivity in LiveOne ---> $it")
mediatorLive.value = "one >>" to it
}
mediatorLive.addSource(liveTwo) {
Log.d("LiveActivity", "LiveActivity in LiveTwo ---> $it")
mediatorLive.value = "two >>>>>" to it
}
//switch map combination mediator, Through conditions , Control the selection of data sources , What's simulated here is ,it Digital parity , Control the final output
val swLive = mediatorLive.switchMap {
if (it.second.takeLast(1).toInt() % 2 == 0) liveOne else liveTwo
}
//UI It can be seen that , Whether it's one, still two, Changed words , Only if the conditions are met , Will take effect .
swLive.observe(viewLifecycleOwner, Observer {
tv_switch_live_apple.text = it
Log.w("AppleFragment", "AppleFragment in switchMap ---> $it")
})3、 ... and 、 Use of problem
Use LiveData As event Event Don't fit
scene : adopt liveData Of Event Jump to the details page ;
Manual clicking Trigger observe in true Then jump ;
Back to the home page , be liveData again active, Then jump again .( You should not try to change more than once , Stupid manual reset)
The reason lies in , In time inactive when ,livedata Still holding set Value ( With or without observer), And in active When , to observer.
programme :
Keep only one observer Receive notification message , If you add multiple , Select a .
//Single LiveEvent open class Event<out T> (private val content:T){ var hasHandled = false private set // It has been handled null, If not , Want again fun getContentIfnotHandled():T?{ return if(hasHandled)null else { hasHandled = true content } } // Whether or not it has been handled , All need results fun peekContent():T = content } // Use val liveD = mutableLiveData<Event<String>>() // liveD.observe(this,Observer{ it.getContentIfnotHandled()?.let{ //do something } })class SingleLiveEvent<T> : MutableLiveData<T>() { private val mPending = AtomicBoolean(false) @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { if (hasActiveObservers()) { Log.w( "SingleLiveEvent", "Multiple observers registered but only one will be notified of changes." ) } // Observe the internal MutableLiveData super.observe(owner, Observer { t -> if (mPending.compareAndSet(true, false)) { observer.onChanged(t) } }) } @MainThread override fun setValue(t: T?) { mPending.set(true) super.setValue(t) } /** * Used for cases where T is Void, to make calls cleaner. */ @MainThread fun call() { value = null } }
attach
LiveDataNetWork
public class NetworkLiveData extends LiveData<NetworkInfo> { private final Context mContext; static NetworkLiveData mNetworkLiveData; private NetworkReceiver mNetworkReceiver; private final IntentFilter mIntentFilter; private static final String TAG = "NetworkLiveData"; public NetworkLiveData(Context context) { mContext = context.getApplicationContext(); mNetworkReceiver = new NetworkReceiver(); mIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); } public static NetworkLiveData getInstance(Context context) { if (mNetworkLiveData == null) { mNetworkLiveData = new NetworkLiveData(context); } return mNetworkLiveData; } @Override protected void onActive() { super.onActive(); Log.d(TAG, "onActive:"); mContext.registerReceiver(mNetworkReceiver, mIntentFilter); } @Override protected void onInactive() { super.onInactive(); Log.d(TAG, "onInactive: "); mContext.unregisterReceiver(mNetworkReceiver); } private static class NetworkReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); getInstance(context).setValue(activeNetwork); } } } // Where to use NetworkLiveData.getInstance(this).observe(this, new Observer<NetworkInfo>() { @Override public void onChanged(@Nullable NetworkInfo networkInfo) { Log.d(TAG, "onChanged: networkInfo=" +networkInfo); } });principle
Observer mode
LifeCycle
边栏推荐
- Itext7 uses iexternalsignature container for signature and signature verification
- Quantitative calculation research
- 023(【模板】最小生成树)(最小生成树)
- 【mysql官方文档】死锁
- 257. All paths of binary tree
- Experience container in libvirt
- Summary of development issues
- Optimize interface performance
- ArcGIS application (XXI) ArcMap method of deleting layer specified features
- 实现验证码验证
猜你喜欢

During FTP login, the error "530 login incorrect.login failed" is reported

Vulnhub's Tomato (tomato)

【mysql专项】读锁和写锁

Xiaopeng P7 hit the guardrail and the airbag did not pop up. The official responded that the impact strength did not meet the ejection requirements

Is BigDecimal safe to calculate the amount? Look at these five pits~~

C language improvement article (wchar_t) character type

Raven2 of vulnhub

Momentum of vulnhub

Qt OpenGL 纹理贴图

Unity3d learning notes 5 - create sub mesh
随机推荐
Solve msvcp120d DLL and msvcr120d DLL missing
OpenGL 着色器使用
Shutter: overview of shutter architecture (excerpt)
PHP get the file list and folder list under the folder
Unicode encoding table download
Basic knowledge of OpenGL (sort it out according to your own understanding)
Shell: basic learning
OpenGL 索引缓存对象EBO和线宽模式
安裝electron失敗的解决辦法
Flutter Widget : KeyedSubtree
(构造笔记)GRASP学习心得
shardingSphere分库分表<3>
typeScript
(构造笔记)ADT与OOP
Jsup crawls Baidu Encyclopedia
Use of QT OpenGL camera
4000 word super detailed pointer
Flutter 退出登录二次确认怎么做才更优雅?
Vulnhub narak
ArcGIS application (XXI) ArcMap method of deleting layer specified features





