更改改造响应后,Mediator Live数据未更新

时间:2019-04-08 06:22:26

标签: android mvvm retrofit2 android-livedata mutablelivedata

我在我的应用程序中使用MVVM体系结构组件。任务是添加MVVM的改造。

我每10秒钟就会致电Web服务器以获取响应数据。要更新此值,我正在使用Mediator实时数据。 这是它的代码

public LiveData<LiveResponse.ResponseData> getLiveResponse(String userId, String tokenId, BodyRequest bodyRequest) {
    final MutableLiveData<LiveResponse.ResponseData> liveResponseMutableLiveData = new MutableLiveData<>();
    restApiService.getLiveResponse(userId, tokenId,bodyRequest).enqueue(new Callback<LiveResponse>() {
        @Override
        public void onResponse(@NotNull Call<LiveResponse> call, @NotNull Response<LiveResponse> response) {
            try {
                if (response.body()!=null){
                    if (response.body().isSuccess()){
                        Timber.i(" liveResponseMutableLiveData onResponse:");
                        liveResponseMutableLiveData.setValue(response.body().getResponseData());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(@NotNull Call<LiveResponse> call, @NotNull Throwable t) {
            liveResponseMutableLiveData.setValue(null);
        }
    });
    return liveResponseMutableLiveData;
}

即使响应已更改,我也无法获得更新的值。

以及调用此方法时如何显示进度条,并在视图模型中显示错误(如果有)。

1 个答案:

答案 0 :(得分:0)

YourViewModel.ktx

priv val TAG = YourViewModel :: class.java.name     val observableProject:MutableLiveData = MutableLiveData()     var userID:MutableLiveData = MutableLiveData()

var livedata = ObservableField<LiveResponse.ResponseData>()


fun setID(id: String,token: String,request BodyRequest) {
    this.userID.setValue(id)
    fetchDataFromServer(id,token,request)
}

fun getServerFetchdata() : LiveData<LiveResponse.ResponseData>{
  return livedata

}

private fun fetchDataFromServer(userId : String,tokenId : String,bodyRequest : BodyRequest ) {
    restApiService.getLiveResponse(userId, tokenId,bodyRequest).enqueue(new Callback<LiveResponse>() {
    @Override
    public void onResponse(@NotNull Call<LiveResponse> call, @NotNull Response<LiveResponse> response) {
        try {
            if (response.body()!=null){
                if (response.body().isSuccess()){
                    Timber.i(" liveResponseMutableLiveData onResponse:");
                    livedata.setValue(response.body().getResponseData());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(@NotNull Call<LiveResponse> call, @NotNull Throwable t) {
        liveResponseMutableLiveData.setValue(null);
    }
});

}

MainActivity.java

有趣的getServerdata(){

viewModel.getProjectListdata()。observe(this,Observer {项目->

// Your data recieve here
    })

}