Transform LiveData

这篇具有很好参考价值的文章主要介绍了Transform LiveData。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

查询资料的其中一个场景:
创建一个回调函数,当查询后台的时候,后台有结果了,回调对应的回调函数,并将结果保存到LiveData中。
public class DataModel {
    ...
    public MutableLiveData<List<Repo>> searchRepo(String query) {
        final MutableLiveData<List<Repo>> repos = new MutableLiveData<>();
        githubService.searchRepos(query)
                .enqueue(new Callback<RepoSearchResponse>() {
                    @Override
                    public void onResponse(@NonNull Call<RepoSearchResponse> call, @NonNull Response<RepoSearchResponse> response) {
                        repos.setValue(response.body().getItems());
                    }
                    ...
                });
        return repos;
    }
}
如果 RepoViewModel的部分写成这样:
public class RepoViewModel extends ViewModel {
    ...
    MutableLiveData<List<Repo>> searchRepo(String query) {
        // NO!
        return dataModel.searchRepo(query);
    }
}
这种写法有如下两个问题:
1.当输入新的关键字的时候,DataModel会返回新的LiveData,这样View每次都要去observe新的LiveData
2.当View重新创建的时候,会再次调用searchRepo,于是DataModel又再一次查询,并且返回新的LiveData。
为了避免重复创建LiveData,只使用固定的一个LiveData,可以使用 Transformations改造上述代码:
下述代码repos返回的都是同一个LiveData。Transformations不会使返回的LiveData变成新的对象,因此View一值都是对LiveData做observe的。即解决了上面提到的两个问题。
public class RepoViewModel extends ViewModel {
...
    private final MutableLiveData<String> query = new MutableLiveData<>();
    private final LiveData<List<Repo>> repos;

    public RepoViewModel(final DataModel dataModel) {
        ...
        repos = Transformations.switchMap(query, new Function<String, LiveData<List<Repo>>>() {
            @Override
            public LiveData<List<Repo>> apply(String userInput) {
                return dataModel.searchRepo(userInput);
            }
        });
    }
    ...
    void searchRepo(String userInput) {
        query.setValue(userInput);
    }
}
如果dataModel查询结果可能为null,也就是没有返回值,但是依然需要返回一个backing LiveData,那么,可以使用 AbsentLiveData
/**
* A LiveData class that has {@code null} value.
*/
public class AbsentLiveData extends LiveData {
    private AbsentLiveData() {
        postValue(null);
    }
    public static <T> LiveData<T> create() {
        //noinspection unchecked
        return new AbsentLiveData();
    }
}
repos = Transformations.switchMap(query, new Function<String, LiveData<List<Repo>>>() {
    @Override
    public LiveData<List<Repo>> apply(String userInput) {
        if (TextUtils.isEmpty(userInput)) {
            return AbsentLiveData.create();
        } else {
            return dataModel.searchRepo(userInput);
        }
    }
});
LiveData<Y> switchMap (LiveData<X> trigger,Function<X, LiveData<Y>> func)
Creates a LiveData, let's name it swLiveData, which follows next flow: it reacts on changes of trigger LiveData, applies the given function to new value of trigger LiveData and sets resulting LiveData as a "backing" LiveData to swLiveData. "Backing" LiveData means, that all events emitted by it will retransmitted by swLiveData.
If the given function returns null, then swLiveData is not "backed" by any other LiveData.
The given function func will be executed on the main thread.
创建一个swLiveData,每当triggerLiveData的值发生变化的时候,就使用triggerLiveData的值,应用相应的函数操作,得到的结果,作为swLiveData的值。
 
Consider the case where you have a LiveData containing a user id. Every time there's a new user id emitted, you want to trigger a request to get the user object corresponding to that id, from a repository that also returns a LiveData.
The userIdLiveData is the trigger and the LiveData returned by the repository.getUserById is the "backing" LiveData.
In a scenario where the repository contains User(1, "Jane") and User(2, "John"), when the userIdLiveData value is set to "1", the switchMap will call getUser(1), that will return a LiveData containing the value User(1, "Jane"). So now, the userLiveData will emit User(1, "Jane"). When the user in the repository gets updated to User(1, "Sarah"), the userLiveData gets automatically notified and will emit User(1, "Sarah").
When the setUserId method is called with userId = "2", the value of the userIdLiveData changes and automatically triggers a request for getting the user with id "2" from the repository. So, the userLiveData emits User(2, "John"). The LiveData returned by repository.getUserById(1) is removed as a source.
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));


void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
}

 文章来源地址https://www.toymoban.com/news/detail-564692.html

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

LiveData<Y> map (LiveData<X> source, Function<X, Y> func)
 
Applies the given function on the main thread to each value emitted by source LiveData and returns LiveData, which emits resulting values.
The given function func will be executed on the main thread.
Suppose that you have a LiveData, named userLiveData, that contains user data and you need to display the user name, created by concatenating the first and the last name of the user. You can define a function that handles the name creation, that will be applied to every value emitted by useLiveData.
在主线程上,对源source liveData的每个数值应用函数操作func,返回的一个新的LiveData,包含func操作的结果,比如如下例子代码,
userLiveData作为源,要创建一个新的LiveData,它的每个值是firstname与lastname的合并。
LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
      return user.firstName + " " + user.lastName
});

 

 

 

 

 

到了这里,关于Transform LiveData的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【C++】STL 算法 - transform 变换算法 ① ( transform 函数原型 | 将 一个 或 两个 输入容器 中的元素 变换后 存储到 输出容器 中 )

    std::transform 是 STL 标准模板库 中的一个算法 , 该算法的作用是 用于对 容器 或 指定迭代器范围 的 每个元素 进行 指定的 \\\" 转换操作 \\\" , 并将 \\\" 转换结果 \\\" 存储到另一个容器中 ; std::transform 算法 接受 一个 或 两个输入范围 , 以及一个输出范围 , 并 根据提供的 一元函数对象 或

    2024年01月16日
    浏览(46)
  • el-form实现其中一个填写即可的校验

       

    2024年02月13日
    浏览(34)
  • postman如何发送json请求其中file字段是一个图片

    在Postman中发送一个包含文件(如图片)的JSON请求通常意味着你需要发送一个multipart/form-data请求。因为在JSON中直接嵌入二进制文件数据(如图片)通常不是一个有效的做法。下面是如何在Postman中发送这样的请求的步骤: 打开Postman并创建一个新的请求 。 设置请求类型为 PO

    2024年04月28日
    浏览(22)
  • odi资料库查询sql

    查询接口基本信息: SELECT C.I_POP                                 WID,        C.POP_NAME                              JKMC,        STH.FULL_TEXT                           ODI_INTERFACE_REMARK,        C.I_TXT_POP_LIB                         JKMSID,        P.PROJECT_NAME || \\\'\\\' ||

    2024年02月09日
    浏览(30)
  • 有一个 3*4 的矩阵,找出其中值最大的元素,及其行列号

    首先学会输入二维数组;然后知道如何比较求最大值;最后就是格式问题; 3运行代码: 4总结: 感谢各位的阅读,以上就是“C语言怎么有一个 3*4 的矩阵,找出其中值最大的元素,及其行列号”的内容了,经过本文的学习后,相信大家对C语言这一问题有了更深刻的体会,具

    2024年02月04日
    浏览(35)
  • Unity 之transform.LookAt() 调整一个物体的旋转,使其朝向指定的位置

    transform.LookAt 是 Unity 引擎中 Transform 组件的一个方法,用于调整一个物体的旋转,使其朝向指定的位置。通常情况下,它被用来使一个物体(如摄像机、玩家角色等)朝向另一个物体、位置或方向。以下是关于 transform.LookAt 方法的详细介绍: 方法签名: 参数说明: target :要

    2024年02月09日
    浏览(32)
  • 【线性代数】两个向量组等价,其中一个向量组线性无关,另一个向量组也是线性无关吗?

    两个向量组等价,其中一个向量组线性无关,另一个向量组也是线性无关吗? 不一定,当两个向量组中的向量个数也相同时,结论才成立.若向量个数不相同,结论不成立. 例如: 向量组一:(1,0),(0,1) 向量组二:(1,0),(0,1),(1,1) 两个向量组等价,向量组一线性无关,向量组二线性相关 参考

    2024年02月02日
    浏览(37)
  • # java合并两个list 并去重,指定保留其中一个list的重复数据

    在Java中,有多种方法可以合并两个List并去重,指定保留其中一个List的重复数据。下面介绍几种常见的方法,并附上代码示例。 该方法首先将一个List的所有元素加入到目标List中,然后遍历另一个List,如果目标List中不包含该元素,则将该元素加入到目标List中。最后得到的就

    2024年02月02日
    浏览(42)
  • redis 存储一个map 怎么让map中其中一个值设置过期时间,而不是过期掉整个map?

    🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页 ——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文并茂🦖生动形象🐅简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍专栏》 🐾 学会IDEA常用操作,工作效率翻倍~💐 🌊 《100天精通Golang(基础

    2024年02月06日
    浏览(30)
  • uniapp实现:点击拨打电话,弹出电话号码列表,可以选择其中一个进行拨打

    在uni-app中,使用 uni.showActionSheet 方法实现点击拨打电话的功能,并弹出相关的电话列表供用户选择。 当用户选择了其中一个电话后,会触发success回调函数,并通过res.tapIndex获取用户选择的电话的索引。然后,可以根据索引从电话号码数组中取出对应的电话号码,并使用 un

    2024年02月11日
    浏览(49)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包