javaandroidandroid-mvvmandroid-toastandroid-snackbar

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


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?


Solution

  • Display Toast/snackbar message in view (Activity/Fragment) from viewmodel using LiveData.

    Step:

    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
        }
    })