KunBa
KunBa

Reputation: 255

How to filter a LiveData in Android MVVM architecture after user input?

I have a userlist of type LiveData that is shown in a recyclerview. Once I type something into an edittext, I simply want to filter the list.

I have seen in other examples that people are using Transformations.switchmap and calling something like userRepo.getFilteredList(searchQuery) in there. But since I have a very simple list and search I think it is better to apply the filter in in the viewmodel.

Is there a simple way like it.filter{item.name.contains(s)} to that livedata in the viewmodel? I am grateful for any kind of reference or tip.

Upvotes: 4

Views: 4276

Answers (1)

KunBa
KunBa

Reputation: 255

fun getFilteredList(s: String): LiveData<List<User>> {
    return Transformations.map(userListLiveData) {
        it.filter {
            it.name.contains(s)
        }
    }
}

I sorted it out :) There you go.

Upvotes: 3

Related Questions