How can I observe API call based on user submit button and at same time getValue from edit text which is necessary for submit action?

前端 未结 3 1676
灰色年华
灰色年华 2020-12-22 06:42

The problem is if I\'ll write observe statement in onCreate, it won\'t observe based on user click event. Because I want to only call repository API when user fill value in

3条回答
  •  星月不相逢
    2020-12-22 07:12

    First I will suggest you to Add data binding in your App

    now in your Activity XML do something like this

    
     viewmodel.doneClicked()}"
        ... />
    

    Now in your ViewModel

    //value in key will be same as value in the EditText as it is bidirectional data binding
    public MutableLiveData key = new MutableLiveData<>();
    
    //update this MutableLiveData accordingly
    private MutableLiveData isDataAvailable = new MutableLiveData<>();
    
    //observe this LiveData
    LiveData isDataAvailable(){
        return isDataAvailable;
    }
    
    public void doneClicked(){
        //here you can get value of your "key"
        //this method will call when clicking on the button
        //you can call your custom method from here,
        //also update data in "isDataAvailable"
    }
    
    

    In your Activity

    viewModel.isDataAvailable().observe(this, aBoolean -> {
        //here you will receive change in value of isDataAvailable
    }
    

    PS Your question is not clear at all, and your code is not helpful

    Do you want to observe change in mutableLiveData of getLicenseData(...) inside your viewModel?

    mutableLiveData = manualLicenseRepository.getLicenseData(licenseKey, macAddress, productId);
    

    Please also change the name of this variable to something related the data it is getting, mutableLiveData is not a good variable name

    Edit 1 try this to observe changes in the data, it is recommended to observe LiveData but you can observer MutableLiveData as you have not provided sufficient information I m using your mutableLiveData variable

    In your Activity try this

    viewModel.mutableLiveData.observe(this, license -> {
        //here you can observe changes in your mutableLiveData when It receives data from Repo
        //here license is the object of data inserted into mutableLiveData from repo
    });
    

    Please explain more.

    Hope this will help!

提交回复
热议问题