Wednesday, 19 December 2018

View Model keeps creating instance of Live Data

I created the instance of View Model in onCreate method of an activity.

    ticketViewModel = ViewModelProviders.of(this).get(TicketViewModel.class);

Then i have a method, AddTicket, which uses viewModel to hit a service and on response from viewModel i dismiss loading animation.

 public void addTicket(View view){

     ticketViewModel.AddTicket(id).observe(this, response ->{
                        dismissLoadingAnimation();
    } 

Now after adding a ticket, user can repress the Add Ticket button, and the addTicket() method will be called again.

but this time observer defined in ViewModel gets called 2 times, resulting in 2 network calls, and 2 dismissLoadingAnimation execution.

And if i keep pressing addTicket button, the number of executing observer defined inside ViewModel keep increases.

This is my View Model code.

public class TicketViewModel extends AndroidViewModel implements IServiceResponse {

    MutableLiveData<String> mObservableResponse = new MutableLiveData<String>();


    public MutableLiveData AddTicket(String id){

        JsonObject jsonObject= new JsonObject();
        jsonObject.addProperty("id",  id);

        NetworkUtility networkUtility= new NetworkUtility(this, ADD_TICKET);
        networkUtility.hitService(URL, jsonObject, RequestMethods.POST);

        return mObservableResponse;
    }


     @Override
        public void onServiceResponse(String response, String callType){

        if(serviceTag.equalsIgnoreCase(ADD_TICKET)){    
             mObservableResponse.setValue("success");
        }
    }

}



from View Model keeps creating instance of Live Data

No comments:

Post a Comment