简体   繁体   中英

MutableLiveData is exposed by casting LiveData from ViewModel

I used the code showen below to not expose the MutableLiveData in the main activity

class CalculatorViewModel : ViewModel(){
 private val operation = MutableLiveData<String>()
    val stringOperation :LiveData<String>
        get() = operation
}

but I figured out a way to access the value of MutableLiveData via the LiveData getter and even change it and this is my code to do it:

(viewModel.stringOperation as MutableLiveData).value = ""

MutableLiveData is supposed to be used when you need to modify LiveData outside of your viewmodel. If you don't want it to get exposed from ViewModel, you must use LiveData.

If you look at LiveData class, you will notice that LiveData is an Abstract class , which means you have to extend it before you can use it. For cases such as yours, you would extend LiveData class. In that child class, you would for example call api and and update the value using private methods. So basically your LiveData class will be responsible for loading and updating the data. Check out this link for an example:

https://developer.android.com/topic/libraries/architecture/livedata#extend_livedata

This is how to properly use LiveData class as per documentation:

public class StockLiveData extends LiveData<BigDecimal> {
    private StockManager stockManager;

    private SimplePriceListener listener = new SimplePriceListener() {
        @Override
        public void onPriceChanged(BigDecimal price) {
            setValue(price);
        }
    };

    public StockLiveData(String symbol) {
        stockManager = new StockManager(symbol);
    }

    @Override
    protected void onActive() {
        stockManager.requestPriceUpdates(listener);
    }

    @Override
    protected void onInactive() {
        stockManager.removeUpdates(listener);
    }
}

To sum up, Use MutableLiveData when you want to modify data outside of LiveData/ViewModel. For all other cases, provide your own implementation of LiveData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM