0

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

我每隔 10 秒调用一次网络服务器以获取响应数据。要更新此值,我正在使用 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;
}

即使响应发生了变化,我也面临着获取更新值的问题。

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

4

1 回答 1

0

你的ViewModel.ktx

private 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 { projects ->

// Your data recieve here
    })

}

于 2019-04-08T06:51:48.720 回答