View Model keeps creating instance of Live Data

前端 未结 5 1442
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 16:47

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

    ticketViewModel = ViewModelProviders.of(this).get(TicketViewModel.cl         


        
5条回答
  •  不思量自难忘°
    2021-01-18 17:36

    • The purpose of Viewmodel is to expose observables (Livedata)
    • The purpose of View(Activity/Fragment) is to get these observables and observe them
    • Whenever there is a change in these observables(Livedata) the change is automatically posted to the active subscribed owners(Activity/Fragment), so you need not remove them in onPause/onStop as it is not mandatory

    I can suggest few changes to your code to solve the problem with the above mentioned pointers

    ViewModel

    public class TicketViewModel extends AndroidViewModel implements IServiceResponse {
    
        MutableLiveData mObservableResponse = new MutableLiveData();
    
       public LiveData getResponseLiveData(){
            return mObservableResponse;
            }
    
        public void AddTicket(String id){
    
            JsonObject jsonObject= new JsonObject();
            jsonObject.addProperty("id",  id);
    
            NetworkUtility networkUtility= new NetworkUtility(this, ADD_TICKET);
            networkUtility.hitService(URL, jsonObject, RequestMethods.POST);
    
        }
    
    
         @Override
            public void onServiceResponse(String response, String callType){
    
            if(serviceTag.equalsIgnoreCase(ADD_TICKET)){    
                 mObservableResponse.setValue("success");
            }
        }
    
    }
    

    View

        onCreate(){
        ticketViewModel = ViewModelProviders.of(this).get(TicketViewModel.class);
        observeForResponse();
        }
    
        private void observeForResponse(){
           ticketViewModel.getResponseLiveData().observe(this, response ->{
                                //do what has to be updated in UI
        }
        }
    
    public void addTicket(View view){
         ticketViewModel.AddTicket(id);
        }
    

    Hope this is of help :)

提交回复
热议问题