【问题标题】:Android Architecture Components LiveDataAndroid 架构组件 LiveData
【发布时间】:2018-01-17 17:46:30
【问题描述】:

我正在尝试使用架构组件实现一个简单的应用程序。 我可以使用 Retrofit2 从 RestApi 服务获取信息。 我可以在相应的 Recyclerview 中显示信息,当我旋转手机时,一切正常。 现在我想过滤一种新的对象(按字符串)

有人可以指导我使用 ViewModel,我不知道这样做的最佳做法是什么... 我正在使用 MVVM...

这是我的 ViewModel:

public class ListItemViewModel extends ViewModel {
    private MediatorLiveData<ItemList> mList;
    private MeliRepository meliRepository;

    /* Empty Contructor.
     * To have a ViewModel class with non-empty constructor,
     * I have to create a Factory class which would create instance of you ViewModel and
     * that Factory class has to implement ViewModelProvider.Factory interface.
     */
    public ListItemViewModel(){
        meliRepository = new MeliRepository();
    }

    public LiveData<ItemList> getItemList(String query){
       if(mList == null){
           mList = new MediatorLiveData<>();
           LoadItems(query);
       }
    }

    private void LoadItems(String query){
        String queryToSearch = TextUtils.isEmpty(query) ? "IPOD" : query;

        mList.addSource(
                meliRepository.getItemsByQuery(queryToSearch),
                list -> mList.setValue(list)
        );
    }
}

更新

我通过转换生命周期库中的包解决了这个问题... enter link description here

public class ListItemViewModel extends ViewModel {

    private final MutableLiveData<String> mQuery = new MutableLiveData<>();
    private MeliRepository meliRepository;
    private LiveData<ItemList> mList = Transformations.switchMap(mQuery, text -> {
        return meliRepository.getItemsByQuery(text);
    });

    public ListItemViewModel(MeliRepository repository){
        meliRepository = repository;
    }

    public LiveData<ItemList> getItemList(String query){
       return mList;
    }
}

@John 这是我的解决方案。我正在使用生命周期库,解决方案比我想象的要容易。谢谢!

【问题讨论】:

    标签: android viewmodel android-architecture-components android-livedata


    【解决方案1】:

    我更熟悉在 Kotlin 中执行此操作,但您应该能够轻松地将其转换为 Java(或者现在可能是开始使用 Kotlin 的好时机 :))....适应我在这里的类似模式我相信你会这样做:

    val query: MutableLiveData<String> = MutableLiveData()
    
    val  mList = MediatorLiveData<List<ItemList>>().apply {
        this.addSource(query) {
            this.value = meliRepository.getItemsByQuery(query)
        }
    }
    
    fun setQuery(q: String) {
        query.value = q
    }
    

    我在关注https://github.com/joreilly/galway-bus-android/blob/master/app/src/main/java/com/surrus/galwaybus/ui/viewmodel/BusStopsViewModel.kt时使用这种模式

    【讨论】:

    • 谢谢约翰...我会试试这个!!
    • @Guille 只是好奇你是否能够让它工作?
    • 我还没有尝试...我在空闲时间“学习”android...我会在这个周末尝试并让你知道! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多