【问题标题】:How to transform LiveData<List<User>> to LiveData<List<String>> in ViewModel?如何在 ViewModel 中将 LiveData<List<User>> 转换为 LiveData<List<String>>?
【发布时间】:2020-01-09 12:32:19
【问题描述】:

我有这个 ViewModel 类:

public class MyViewModel extends ViewModel {
    private MyRepository myRepository;

    public MyRepository() {
        myRepository = new MyRepository();
    }

    LiveData<List<String>> getUsersLiveData() {
        LiveData<List<User>> usersLiveData = myRepository.getUserList();
        return Transformations.switchMap(usersLiveData, userList -> {
            return ??
        });
    }
}

MyRepository 类a 中,我有一个方法getUserList(),它返回一个LiveData&lt;List&lt;User&gt;&gt; 对象。如何将此对象转换为LiveData&lt;List&lt;String&gt;&gt;,它基本上应该包含一个字符串列表(用户名)。我的User 类只有两个字段,nameid。谢谢。

【问题讨论】:

  • 获取String类型的变量ArrayList,然后通过迭代将userList中的所有name添加到其中,然后从回调中返回新创建的列表。
  • @JeelVankhede 我想过这一点,但使用Transformations.switchMap 没有其他可能性吗?因为我想直接转换 LiveData> 对象。谢谢
  • 您是否尝试过使用Transformations.map
  • @SanlokLee 我没有。那怎么能用呢?谢谢

标签: java android android-livedata android-viewmodel


【解决方案1】:

您需要的是一个简单的mapTransformation.switchMap 用于连接到不同的LiveData。示例:

    LiveData<List<String>> getUsersLiveData() {
        LiveData<List<User>> usersLiveData = myRepository.getUserList();
        return Transformations.map(usersLiveData, userList -> {
            return userList.stream().map(user -> user.name).collect(Collectors.toList());
        });
    }

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多