Skip to content
Advertisement

Toast message inside MutableLiveData.observe() working repeatedly

I have a register form and ı want to show a message to the user based on signed up successfully or not.I store that message in my view model which has a mutable live data object to store that message and observing that object from my activity.My problem is when ı click to the register button first time it works normally,showing Toast with my message as expected but when ı click that button again Toast message show my message two times.I really didn’t understand what’s wrong with my code.Here is my code.

RegisterActivity

JavaScript

RegisterActivityViewModel

JavaScript

Advertisement

Answer

Because the “register” function creates a new observer everytime it gets called. This is the observer:

JavaScript

Everytime the button get clicked the function add a new observer on the MutableLiveData “signUpData”:

JavaScript

So if you move the “observe” function into the “OnCreateView” event the problem should be solved, because the fragment will register only 1 observer when the view gets created and not when the button gets clicked. Another option would be to delete the observer after the toast message has been delivered:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement