首页 > 解决方案 > LiveData、MVVM 和存储库模式

问题描述

这是一个好方法还是我刚刚找到了一个讨厌的解决方法?

我正在使用MediatorLiveData类,因为似乎对更新LiveData对象的源很有用。

我的意思是,我在互联网上找到的大多数教程都只是使用LivedataMutableLivedata不使用动态源,例如:

fun search(/*no input params*/): Call<List<Person>>

但就我而言,我有以下按名称执行搜索的 Web 服务:

interface APIServidor {
    @GET("search")
    fun search(@Query("name") name: String): Call<List<Person>>

}

public class PeopleRepository {


    public LiveData<List<Person>> search(String name){

        final MutableLiveData<List<Person>> apiResponse = new MutableLiveData<>();
        Call<List<Person>> call = RetrofitService.Companion.getInstance().getApiServer().search(name);
        call.enqueue(new Callback<List<Person>>() {
            @Override
            public void onResponse(@NonNull Call<List<Person>> call, @NonNull Response<List<Person>> response) {
                if (response.isSuccessful()) {
                    apiResponse.postValue(response.body());
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Person>> call, @NonNull Throwable t) {
                apiResponse.postValue(null);
            }
        });

        return apiResponse;
    }
}

然后在 viewmodel 类中,我为每个新请求添加源。

public class SearchViewModel extends ViewModel {

    private MediatorLiveData<List<Person>> mApiResponse;
    private PeopleRepository mApiRepo;

    public SearchViewModel() {
        mApiResponse = new MediatorLiveData<>();
        mApiRepo = new PeopleRepository();
    }

    public LiveData<List<Person>> getPlayers() {
        return mApiResponse;
    }

    public void performSearch(String name){
        mApiResponse.addSource(mApiRepo.search(name), new Observer<List<Person>>() {
            @Override
            public void onChanged(List<Person> apiResponse)            {
                mApiResponse.setValue(apiResponse);
            }
        });
    }
}

活动

bt_search.setOnClickListener {
    val player_name = et_player.text.toString()
    viewModel.performSearch(player_name)
}

项目范围

我在一个个人项目中

目标

使用 MVVM + 实时数据 + 存储库模式

问题

我只找到了一种简单方法的教程:观察一个LiveData访问repository对象并只获取一次数据的对象。

select * from people例如:从 Web 服务获取所有人 ( )。

select * from people where name=?我的案例:从 Web 服务中获取具有姓名 ( ) 的人。

https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890 https://medium.com/@sriramr083/error-handling-in-retrofit2-in -mvvm-repository-pattern-a9c13c8f3995

怀疑

对用户输入MediatorLiveData的所有请求使用类是个好主意吗?merge

我应该使用MutableLiveData和更改repository课程并使用自定义的clousure吗?

有更好的方法吗?

标签: androidmvvmkotlinrepository-patternandroid-livedata

解决方案


我也将这种模式与 MediatorLiveData 一起使用,但它形成了一个问题。从用户的角度来看,它似乎运行得很好,但这里的一个问题是每次调用performSearch()存储库时都会创建一个新的 LiveData 对象,该对象还会通过addSource().

一个想法可能是让存储库只创建一次 MutableLiveData 对象,并在连续调用时更新它的值。所以 feMutableLiveData<List<Person>> apiResponse;将是一个未初始化的私有字段,在search()方法中被初始化。

例如。if (apiResponse == null) apiResponse = new MutableLiveData();


推荐阅读