Pathis Patel
Pathis Patel

Reputation: 179

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.

Upvotes: 1

Views: 1907

Answers (1)

Sanlok Lee
Sanlok Lee

Reputation: 3494

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

Upvotes: 1

Related Questions