简体   繁体   English

如何在 ViewModel 中对 MutableLiveData ArrayList 进行排序?

[英]How to sort MutableLiveData ArrayList in ViewModel?

I have an Android app (Java) that makes an api call for shows.我有一个 Android 应用程序 (Java),它可以让 api 调用节目。 After the shows are returned, I need to filter the show arraylist by season & then by episode.返回节目后,我需要按季节和剧集过滤节目 arraylist。 I'm currently sorting the list in my fragment because I haven't found a good solution on how to do this in my viewmodel.我目前正在对我的片段中的列表进行排序,因为我还没有在我的视图模型中找到一个很好的解决方案。

This is my call in my vm:这是我在我的虚拟机中的电话:

public MutableLiveData<ArrayList<Titles>> getTitlesListLiveData(){
    return repository.getTitlesLiveData();
} 

And this is how I'm sorting it in my fragment:这就是我在片段中对其进行排序的方式:

    titlesViewModel.titlesListLiveData.observe(getViewLifecycleOwner(), titles -> {

        for (Titles title : titles) {
            titlesList.add(title);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            titlesList.sort(Comparator.comparing(Titles::getSeasonNumber).thenComparing(Titles::getEpisodeNumber));
        }
        binding.rvTitles.setAdapter(ShowTitlesAdapter);            
        ShowTitlesAdapter.setShowTitlesList(titlesList);

    });
    titlesViewModel.getAllTitles(ShowTag);

I find this but I don't understand how I would do it in Java or in my viewmodel.我发现了这一点,但我不明白如何在 Java 或我的视图模型中做到这一点。 Can anyone help?任何人都可以帮忙吗?

Just use the LiveData Transformations .只需使用LiveData 转换 In your case it could be something like this:在你的情况下,它可能是这样的:

public LiveData<List<Titles>> getTitlesListLiveData()
{
    return Transformations.map( repository.getTitlesLiveData(), titles ->
            titles.sort(Comparator.comparing(Titles::getSeasonNumber).thenComparing(Titles::getEpisodeNumber))
    );
}

Also you don't have to set the adapter every time the data changes:此外,您不必在每次数据更改时都设置适配器:

binding.rvTitles.setAdapter(ShowTitlesAdapter);

You can set it once, for example in the onCreate (when in Activity) or in onCreateView (when in Fragment).您可以设置一次,例如在 onCreate(在 Activity 中时)或在 onCreateView(在 Fragment 中时)。 Then when the data changes you just call the setShowTitlesList to change the data in adapter然后当数据更改时,您只需调用setShowTitlesList来更改适配器中的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM