[英]Making a generic network adapter using livedata, retrofit, mvvm and repository pattern
[英]LiveData, MVVM and Repository Pattern
這是一個好方法還是我剛剛找到了一個討厭的解決方法?
我正在使用MediatorLiveData
類,因為似乎對更新LiveData
對象的源很有用。
我的意思是,我在互聯網上找到的大多數教程Livedata
使用Livedata
或MutableLivedata
而沒有動態源,例如:
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 +實時數據+存儲庫模式
我只發現了一種使用簡單方法的教程:觀察一個訪問repository
對象的LiveData
對象,並且只獲取一次數據。
在示例中:從Web服務獲取所有人( select * from people
)。
我的情況是:從Web服務中獲取具有名稱的人( select * from people where name=?
)。
https://medium.com/@elye.project/kotlin-and-retrofit-2-tutorial-with-working-codes-333a4422a890 https://medium.com/@sriramr083/error-handling-in-retrofit2-in -mvvm-庫圖案a9c13c8f3995
一個好主意是使用MediatorLiveData
類來merge
所有來自用戶輸入的請求嗎?
我應該使用MutableLiveData
並更改repository
類並使用自定義的clousure嗎?
有沒有更好的方法?
我也將這種模式與MediatorLiveData一起使用,但這構成了一個問題。 從用戶角度看,它似乎還可以正常工作,但是這里的一個問題是,每次調用performSearch()
,存儲庫都會創建一個新的LiveData對象,該對象還通過addSource()
添加到MediatorLiveData中。
一個想法可能是讓存儲庫僅創建一次MutableLiveData對象,並且在連續調用時只需更新其值即可。 因此, MutableLiveData<List<Person>> apiResponse;
將是在search()
方法中初始化的未初始化的私有字段。
例如。 if (apiResponse == null) apiResponse = new MutableLiveData();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.