【发布时间】: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<List<User>> 对象。如何将此对象转换为LiveData<List<String>>,它基本上应该包含一个字符串列表(用户名)。我的User 类只有两个字段,name 和id。谢谢。
【问题讨论】:
-
获取
String类型的变量ArrayList,然后通过迭代将userList中的所有name添加到其中,然后从回调中返回新创建的列表。 -
@JeelVankhede 我想过这一点,但使用
Transformations.switchMap没有其他可能性吗?因为我想直接转换 LiveData- > 对象。谢谢
-
您是否尝试过使用
Transformations.map? -
@SanlokLee 我没有。那怎么能用呢?谢谢
标签: java android android-livedata android-viewmodel