Android Architecture Components LiveData

2019-08-04 06:51发布

I'm trying to implement a simple App using Architecture Components. I can get the info from RestApi services using Retrofit2. I can show the info in the respective Recyclerview and when I rotate the phone everything works as it should. Now I want to filter by a new kind of object (by string)

Can someone guide me a little with the ViewModel, I don't know what is the best practice to do that... I'm using MVVM...

This is my 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)
        );
    }
}

UPDATE

I resolved this using transformation a package from lifecycle library... 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 this is my solution. I'm using lifecycle library and the solution was easier than I thought. Thx!

1条回答
聊天终结者
2楼-- · 2019-08-04 07:37

I'm more familiar with doing this in Kotlin but you should be able to translate this to Java easily enough (or perhaps now is a good time to start using Kotlin :) )....adapting similar pattern I have here I believe you'd do something like:

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
}

I'm using this pattern in following https://github.com/joreilly/galway-bus-android/blob/master/app/src/main/java/com/surrus/galwaybus/ui/viewmodel/BusStopsViewModel.kt

查看更多
登录 后发表回答