Search code examples
javaandroidandroid-livedataandroid-viewmodel

How to transform LiveData<List<User>> to LiveData<List<String>> in ViewModel?


I have this ViewModel class:

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 ??
        });
    }
}

In MyRepository class a I have a method getUserList() that returns a LiveData<List<User>> object. How can I transform this object to LiveData<List<String>>, which basically should contain a list of strings (user names). My User class has only two fields, name and id. Thanks.


Solution

  • What you need is a simple map. Transformation.switchMap is for connecting to a different LiveData. Example:

        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());
            });
        }