Java 如何转换LiveData<;列表<;用户>&燃气轮机;到LiveData<;列表<;字符串>&燃气轮机;在ViewModel中?

Java 如何转换LiveData<;列表<;用户>&燃气轮机;到LiveData<;列表<;字符串>&燃气轮机;在ViewModel中?,java,android,android-livedata,android-viewmodel,Java,Android,Android Livedata,Android Viewmodel,我有一个ViewModel类: public class MyViewModel extends ViewModel { private MyRepository myRepository; public MyRepository() { myRepository = new MyRepository(); } LiveData<List<String>> getUsersLiveData() { Liv

我有一个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 ??
        });
    }
}
公共类MyViewModel扩展了ViewModel{
私有MyRepository MyRepository;
公共MyRepository(){
myRepository=新建myRepository();
}
LiveData getUsersLiveData(){
LiveData usersLiveData=myRepository.getUserList();
返回Transformations.switchMap(usersLiveData,userList->{
返回??
});
}
}

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

您需要的是一张简单的
地图<代码>转换。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());
        });
    }
LiveData getUsersLiveData(){
LiveData usersLiveData=myRepository.getUserList();
返回Transformations.map(usersLiveData,userList->{
返回userList.stream().map(user->user.name).collect(Collectors.toList());
});
}

获取
String
类型的变量
ArrayList
,然后通过迭代将
userList
中的所有
名称添加到其中,然后从回调返回新创建的列表。@JeelVankhede我考虑过这一点,但使用
转换没有其他可能性。switchMap
?因为我想直接转换LiveData对象。谢谢你试过使用
转换。map
?@SanlokLee我没有。你怎么能用这个?谢谢