当前位置:网站首页>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
rxjava
Observation mode , Only the notification is inactive
State observer .Once the observer replies
Resume
state , 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
边栏推荐
- Solution à la défaillance de l'installation d'Electron
- Wechat applet development - page Jump transfer parameters
- DEJA_VU3D - Cesium功能集 之 053-地下模式效果
- typeScript
- PHP get the file list and folder list under the folder
- Why can't my MySQL container start
- Vulnhub geminiinc V2
- Dart: About zone
- 【附下载】密码获取工具LaZagne安装及使用
- ArcGIS application (XXI) ArcMap method of deleting layer specified features
猜你喜欢
Introduction to the implementation principle of rxjs observable filter operator
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
Vulnhub's Tomato (tomato)
Fluent: Engine Architecture
使用BLoC 构建 Flutter的页面实例
Shardingsphere sub database and sub table < 3 >
Kubernetes three dozen probes and probe mode
Ripper of vulnhub
New features of ES6
OPenGL 基本知识(根据自己理解整理)
随机推荐
Slf4j log facade
AOSP ~ NTP (Network Time Protocol)
PHP导出word方法(一phpword)
Shutter: add gradient stroke to font
Simple factory and factory method mode
Experience container in libvirt
PHP export word method (one MHT)
Duplicate numbers in the array of sword finger offer 03
(构造笔记)从类、API、框架三个层面学习如何设计可复用软件实体的具体技术
Vulnhub geminiinc V2
PHP get the file list and folder list under the folder
(構造筆記)從類、API、框架三個層面學習如何設計可複用軟件實體的具體技術
During FTP login, the error "530 login incorrect.login failed" is reported
225. Implement stack with queue
[combinatorics] permutation and combination (summary of permutation and combination content | selection problem | set permutation | set combination)
[learning notes] DP status and transfer
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
OpenGL shader use
Unity3d learning notes 5 - create sub mesh
LeetCode 0556.下一个更大元素 III - 4步讲完