View Model keeps creating instance of Live Data

前端 未结 5 1409
隐瞒了意图╮
隐瞒了意图╮ 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:35

    If you are willing to do some changes, i think we can handle it in much cleaner way

    LiveData is meant to be used to contain a property value of a view


    In ViewModel

    public class TicketViewModel extends AndroidViewModel implements IServiceResponse {
    
        private MutableLiveData showLoadingAnimationLiveData = new MutableLiveData();
    
        public LiveData getShowLoadingAnimationLiveData(){
            return showLoadingAnimationLiveData;
        }
    
        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);
            showLoadingAnimationLiveData.setValue(true);
        }
    
    
        @Override
        public void onServiceResponse(String response, String callType){
            if(serviceTag.equalsIgnoreCase(ADD_TICKET)){    
                showLoadingAnimationLiveData.setValue(false);
            }
        }
    
    }
    

    In 'onCreate' of your Activity/Fragment

    ticketViewModel.getShowLoadingAnimationLiveData().observe(this,showLoadingAnimation->{
        if(showLoadingAnimation != null && showLoadingAnimation){
            startLoadingAnimation();
        }else{
            dismissLoadingAnimation();
        }
    })
    

    The main concept is to divide the responsibilities, Activity/Fragment doesn't need to know which process is going on, they only need to know what are the current properties/state of there child views.

    We need to maintain a LiveData in ViewModels for each changing property/state depending on Views. ViewModel needs to handle the view states depending on whats happening.

    Only responsibility the Activity/Fragment has about a process is to trigger it and forget and ViewModel needs handle everything(like informing Repositories to do the work and changing View Properties).

    In your Case, 'addTicket' is a process about which Activity/Fragment doesn't need to know about there status. The only responsibility of Activity/Fragment about that process is to trigger it.

    ViewModel is one who needs to analyze the state of process(in-progress/success/failed) and give appropriate values to the LiveDatas to inform the respective Views

提交回复
热议问题