LiveData常用方法源码分析

2023-12-26 04:08

本文主要是介绍LiveData常用方法源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、postValue
protected void postValue(T value) {boolean postTask;// 同步锁synchronized (mDataLock) {// 判断mPendingData是否为NOT_SETpostTask = mPendingData == NOT_SET;// 对mPendingData赋值mPendingData = value;}// 防止数据重复设置if (!postTask) {return;}// 将数据发送到主线程处理ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);}

步骤分解:

  • 1、LiveData通过postValue方法在子线程同步方法中设置数据
  • 2、数据NOT_SET校验
  • 3、将数据发送到主线程进行处理
2、setValue
 @MainThreadprotected void setValue(T value) {assertMainThread("setValue"); // 1mVersion++; // 2mData = value; // 3dispatchingValue(null); // 4}

步骤分解:

  • 1、主线程校验
  • 2、计数器自加
  • 3、为mData赋值
  • 4、分发数据(详见dispatchingValue)
3、assertMainThread 主线程校验
 static void assertMainThread(String methodName) {if (!ArchTaskExecutor.getInstance().isMainThread()) {throw new IllegalStateException("Cannot invoke " + methodName + " on a background"+ " thread");}}
4、dispatchingValue
   void dispatchingValue(@Nullable ObserverWrapper initiator) {// 1if (mDispatchingValue) {mDispatchInvalidated = true;return;}// 2mDispatchingValue = true;do {mDispatchInvalidated = false;// 3if (initiator != null) {considerNotify(initiator);initiator = null;} else {// 4for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {considerNotify(iterator.next().getValue());if (mDispatchInvalidated) {break;}}}} while (mDispatchInvalidated);mDispatchingValue = false;}

步骤分解:

  • 1、分发状态标记,防止重复分发
  • 2、修改分发状态
  • 3、分发通过参数传递进来的迭代器中数据
  • 4、将数据分发给所有观察者
5、considerNotify
 private void considerNotify(ObserverWrapper observer) {// 1if (!observer.mActive) {return;}// Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.//// we still first check observer.active to keep it as the entrance for events. So even if// the observer moved to an active state, if we've not received that event, we better not// notify for a more predictable notification order.// 2if (!observer.shouldBeActive()) {observer.activeStateChanged(false);return;}// 3if (observer.mLastVersion >= mVersion) {return;}// 4observer.mLastVersion = mVersion;// 5observer.mObserver.onChanged((T) mData);}

步骤分解

  • 1、观察者非active状态,拦截
  • 2、通过shouldBeActive修改观察者active状态
  • 3、version计数器比对
  • 4、调用onChange方法,分发数据
6、observe
  @MainThreadpublic void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {assertMainThread("observe");// 1if (owner.getLifecycle().getCurrentState() == DESTROYED) {// ignorereturn;}// 2LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);// 3ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);// 4if (existing != null && !existing.isAttachedTo(owner)) {throw new IllegalArgumentException("Cannot add the same observer"+ " with different lifecycles");}if (existing != null) {return;}// 5owner.getLifecycle().addObserver(wrapper);}

步骤分解

  • 1、如果owner为DESTROYED状态,直接return
  • 2、构造LifecycleBoundObserver
  • 3、构造ObserverWrapper(详见putIfAbsent)
  • 4、对已经存在观察者抛出异常,防止重复添加监听
  • 5、添加合法观察者
7、putIfAbsent
  public V putIfAbsent(@NonNull K key, @NonNull V v) {Entry<K, V> entry = get(key);if (entry != null) {return entry.mValue;}put(key, v);return null;}
  • Entry形式存储K、V值,K不允许重复
8、map
 public static <X, Y> LiveData<Y> map(@NonNull LiveData<X> source,@NonNull final Function<X, Y> mapFunction) {// 1final MediatorLiveData<Y> result = new MediatorLiveData<>();// 2result.addSource(source, new Observer<X>() {@Overridepublic void onChanged(@Nullable X x) {// 3result.setValue(mapFunction.apply(x));}});// 4return result;}

步骤分解

  • 1、创建MediatorLiveData
  • 2、通过addSource将源数据添加到result中
  • 3、为result添加源数据监听,并在接收到监听后setValue
  • 4、返回MediatorLiveData类型数据作为result
9、switchMap
 @MainThread@NonNullpublic static <X, Y> LiveData<Y> switchMap(@NonNull LiveData<X> source,@NonNull final Function<X, LiveData<Y>> switchMapFunction) {// 1final MediatorLiveData<Y> result = new MediatorLiveData<>();// 2result.addSource(source, new Observer<X>() {LiveData<Y> mSource;@Overridepublic void onChanged(@Nullable X x) {// 3LiveData<Y> newLiveData = switchMapFunction.apply(x);// 4if (mSource == newLiveData) {return;}// 5if (mSource != null) {result.removeSource(mSource);}// 6mSource = newLiveData;// 7if (mSource != null) {result.addSource(mSource, new Observer<Y>() {@Overridepublic void onChanged(@Nullable Y y) {// 8result.setValue(y);}});}}});// 9return result;}

步骤分解

  • 1、创建MediatorLiveData类型result
  • 2、将源数据添加到result中
  • 3、通过switchMapFunction的apply函数创建LiveData类型数据newLiveData
  • 4、与前一次的数据相同,直接返回
  • 5、数据不为空,通过removeSource方法将数据从result中移除
  • 6、缓存newLiveData至mSource
  • 7、mSource不为空,将mSource作为源数据添加到result中
  • 8、为result添加源数据mSource监听,并在接收到监听后setValue
  • 9、返回MediatorLiveData类型数据result
10、addSource
 @MainThreadpublic <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {// 1Source<S> e = new Source<>(source, onChanged);// 2Source<?> existing = mSources.putIfAbsent(source, e);// 3if (existing != null && existing.mObserver != onChanged) {throw new IllegalArgumentException("This source was already added with the different observer");}// 4if (existing != null) {return;}// 5if (hasActiveObservers()) {e.plug(); // 6}}

步骤分解

  • 1、以source和onChanged构造Source类型数据e
  • 2、以源数据source和e构造新的Source类型数据existing
  • 3、如果existing数据存在,也就是说之前已经为source添加过观察者情况,抛异常
  • 4、重复判断existing,进行返回
  • 5、如果有active的Observers,添加监听
  • 6、plug方法(详见plug)
11、plug() MediatorLiveData中
 void plug() {mLiveData.observeForever(this);}
  • observeForever
  /*** Adds the given observer to the observers list. This call is similar to* {@link LiveData#observe(LifecycleOwner, Observer)} with a LifecycleOwner, which* is always active. This means that the given observer will receive all events and will never* be automatically removed. You should manually call {@link #removeObserver(Observer)} to stop* observing this LiveData.* While LiveData has one of such observers, it will be considered* as active.* <p>* If the observer was already added with an owner to this LiveData, LiveData throws an* {@link IllegalArgumentException}.** @param observer The observer that will receive the events*/@MainThreadpublic void observeForever(@NonNull Observer<? super T> observer) {assertMainThread("observeForever");// 1AlwaysActiveObserver wrapper = new AlwaysActiveObserver(observer);// 2ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);// 3if (existing instanceof LiveData.LifecycleBoundObserver) {throw new IllegalArgumentException("Cannot add the same observer"+ " with different lifecycles");}if (existing != null) {return;}// 4wrapper.activeStateChanged(true);}
  • 1、 通过observer构造AlwaysActiveObserver
  • 2、 通过observer和wrapper构造ObserverWrapper类型数据existing
  • 3、 如果existing数据已经存在,也就是说LiveData已经添加过该observer了,抛出异常
  • 4、修改wrapper的active状态为true

这篇关于LiveData常用方法源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/538038

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

在Golang中实现定时任务的几种高效方法

《在Golang中实现定时任务的几种高效方法》本文将详细介绍在Golang中实现定时任务的几种高效方法,包括time包中的Ticker和Timer、第三方库cron的使用,以及基于channel和go... 目录背景介绍目的和范围预期读者文档结构概述术语表核心概念与联系故事引入核心概念解释核心概念之间的关系

在Linux终端中统计非二进制文件行数的实现方法

《在Linux终端中统计非二进制文件行数的实现方法》在Linux系统中,有时需要统计非二进制文件(如CSV、TXT文件)的行数,而不希望手动打开文件进行查看,例如,在处理大型日志文件、数据文件时,了解... 目录在linux终端中统计非二进制文件的行数技术背景实现步骤1. 使用wc命令2. 使用grep命令