-2

When I want to use Toast with MVVM,

In ViewModel

public MutableLiveData<String> setToast(){

    return ToTo;

}

public void ShowToast(String t){

    ToTo.postValue(t);

}

Put the code in this way.

In View

model.setToast().observe(this, ob_toast ->{

    Toast.makeText(getApplicationContext(), ob_toast, Toast.LENGTH_SHORT).show();

});

I used to coding like this.

Whenever I need it, I call the function 'ShowToast' from the ViewModel and write it. but I don't know if this is right.

need to create a class of Util functions?

I wonder if there is a pattern or a way to use it more easily.

JH Hwang
  • 29
  • 5

1 Answers1

1

I would recommend to not put Toast in your ViewModel class because it's an improper way to put context related stuff into ViewModel. Instead you can observe MutableLiveData variables in a context class (Fragment or Activity) and there generate and show your Toast depending on values from MutableLiveData.