使用 MVVM 模式显示和隐藏进度条

Display and hide progress bar using MVVM pattern

我正在使用 MVVM 模式。我刚开始,我已经成功了。

但我不明白如何像我们通常为 API 调用一样添加用于显示和隐藏的进度条。

我没有使用数据绑定。那么如何使用进度条显示和隐藏呢

待登录

public class LoginRepository {

private DATAModel dataModel = new DATAModel();
private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
private Application application;

public LoginRepository(Application application) {
    this.application = application;
}

public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {

    APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);

    JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);

    Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
    call.enqueue(new Callback<APIResponseLogin>() {
        @Override
        public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
            APIResponseLogin apiResponse = response.body();
            if (apiResponse != null && apiResponse.getStatuscode() == 0) {
                if (apiResponse.getDataModel() != null) {
                    dataModel = apiResponse.getDataModel();
                    mutableLiveData.setValue(dataModel);
                }

            } else if (apiResponse != null && apiResponse.getStatuscode() == 1) {

                Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
            }
        }

        @Override
        public void onFailure(Call<APIResponseLogin> call, Throwable t) {

            Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
        }
    });
    return mutableLiveData;
}

Activity代码

void loginCall() {
    loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
        @Override
        public void onChanged(@Nullable DATAModel dataModel) {
            if (dataModel != null) {
                Userdetails userdetails = dataModel.getUserdetails();
                List<ContactTypes> contactTypes = dataModel.getContactTypes();
                if (userdetails != null) {

                    MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
                    MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
                }

                if (contactTypes != null) {
                    MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
                }

                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }
    });
}

高级帮助将不胜感激!

When you call api that time you have to take one live variable which shows your api is in loading mode or not and after success or failure you have to update that variable.

After observe that variable in your activity or fragment class and show or hide your progress.

public class LoginRepository {
    
      private DATAModel dataModel = new DATAModel();
      private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
      private Application application;
      private MutableLiveData<Boolean> progressbarObservable;
    
      public LoginRepository(Application application) {
          this.application = application;
      }

      public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {
         // add below line
         progressbarObservable.value = true
         APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);

    JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);

    Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
    call.enqueue(new Callback<APIResponseLogin>() {
        @Override
        public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
            // add below line
            progressbarObservable.value = false
            APIResponseLogin apiResponse = response.body();
            if (apiResponse != null && apiResponse.getStatuscode() == 0) {
                if (apiResponse.getDataModel() != null) {
                    dataModel = apiResponse.getDataModel();
                    mutableLiveData.setValue(dataModel);
                }

            } else if (apiResponse != null && apiResponse.getStatuscode() == 1) {

                Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
            }
        }

        @Override
        public void onFailure(Call<APIResponseLogin> call, Throwable t) {
            // add below line
            progressbarObservable.value = false
            Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
        }
    });
    return mutableLiveData;
    }
    }

Now, observe above variable in activity or fragment and based on that value hide or show your progress bar

    public class LoginActivity extends AppCompatActivity {
      ...
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        ...
        
        observeLogin();
      }

       @Override
       public void onClick(View view) 
       { 
         switch (view.getId()) { 
            case R.id.button_login: 
            // Do something 
            loginCall();
          } 
       } 
      
      private void observeLogin() {
        loginViewModel.progressbarObservable().observe(this, new  Observer<Boolean>() {
          @Override
          public void onChanged(final Boolean progressObserve) {
            if(progressObserve){
               show your progress
            }
            else {
               hide your progress
            }
          }
        });
      }

void loginCall() {
    loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
        @Override
        public void onChanged(@Nullable DATAModel dataModel) {
            if (dataModel != null) {
                Userdetails userdetails = dataModel.getUserdetails();
                List<ContactTypes> contactTypes = dataModel.getContactTypes();
                if (userdetails != null) {

                    MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
                    MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
                }

                if (contactTypes != null) {
                    MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
                }

                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }
    });
}
      
    }

我发现在这种情况下编写自己的回调接口更容易。只是这不是同步完成的,所以一切都会等到您的 api 呼叫响应。但在这种情况下,进度对话框会产生类似的效果。

1.Create 界面:

public interface ProgressCallback{  
  void onDone(String message);

   void onFail(String message); 
}
  1. 现在在调用 API
  2. 的方法中

loginUser(String name, String password, ProgressCallback progressCallback){

    call.enqueue(new Callback<LoginData>() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onResponse(Call<LoginData> call, Response<LoginData>           response) {
                    progressCallBack.onSuccess(response.message());
                }
    
            @Override
            public void onFailure(Call<LoginData> call, Throwable t) {
    
                progressCallBack.onFail(t.getMessage());
            }
        });
  1. 现在当你调用方法时
loginUser("John@doe.com", "applesgravity", new ProgressCallBack() {
                   @Override
                   public void onSuccess(String message) {
                       progressBar.setVisibility(View.INVISIBLE);
                   }

                   @Override
                   public void onFail(String message) {
                       progressBar.setVisibility(View.INVISIBLE);
                   }
               });