Android: MVVM is it possible to display a message (toast/snackbar etc.) from the ViewModel

user3182266 picture user3182266 · Nov 26, 2018 · Viewed 10.5k times · Source

I want to know what is the best approach to display some sort of message in the view from the ViewModel. My ViewModel is making a POST call and "onResult" I want to pop up a message to the user containing a certain message.

This is my ViewModel:

public class RegisterViewModel extends ViewModel implements Observable {
.
.   
.
public void registerUser(PostUserRegDao postUserRegDao) {

    repository.executeRegistration(postUserRegDao).enqueue(new Callback<RegistratedUserDTO>() {
        @Override
        public void onResponse(Call<RegistratedUserDTO> call, Response<RegistratedUserDTO> response) {
            RegistratedUserDTO registratedUserDTO = response.body();
            /// here I want to set the message and send it to the Activity

            if (registratedUserDTO.getRegisterUserResultDTO().getError() != null) {

            }
        }

    });
}

And my Activity:

public class RegisterActivity extends BaseActivity {   

@Override
protected int layoutRes() {
    return R.layout.activity_register;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    AndroidInjection.inject(this);
    super.onCreate(savedInstanceState);

    ActivityRegisterBinding binding = DataBindingUtil.setContentView(this, layoutRes());
    binding.setViewModel(mRegisterViewModel);       
}

What would the best approach be in this case?

Answer

Mitesh Vanaliya picture Mitesh Vanaliya · Nov 30, 2018

Display sort of message in view from viewmodel using LiveData.

Step:

  • Add LiveData into your viewmodel
  • View just observe LiveData and update view related task

For example:

In Viewmodel:

var status = MutableLiveData<Boolean?>()
//In your network successfull response
status.value = true

In your Activity or fragment:

yourViewModelObject.status.observe(this, Observer { status ->
    status?.let {
        //Reset status value at first to prevent multitriggering
        //and to be available to trigger action again
        yourViewModelObject.status.value = null
        //Display Toast or snackbar
    }
})