0

Let's say we have the stock of items stored in the JSON txt file. To access the data we load JSON file using a stringBuilder class, then populate StokItems into:

List<StockItem> stock;

like this:


                stock.clear();

                Gson gson = new Gson();

                stock = gson.fromJson(stringBuilder.toString(), new TypeToken<List<StockItem>>() {
                }.getType());


as we would like to take advantage of the LiveData in Android we introduced:

MutableLiveData<List<StockItem>> stockLiveData = new MutableLiveData<>();

To make it working we have to post data into it:

    public LiveData<List<StockItem>> getLiveStockList() {
        stockLiveData.postValue(stock);
        return stockLiveData;
    }

So here is the question, if the line:

        stockLiveData.postValue(stock);

consumes memory for creating another copy of

 List<StockItem> stock

and if so, could be it's a good idea to keep "original data" inside the

 stockLiveData

variable only to reduce the memory impact? (If is it possible ...)

Paul Paku
  • 360
  • 2
  • 16

2 Answers2

0

No need to use global variable to hold temporary data. either you can use local variable or directly post to LiveData.

public LiveData<List<StockItem>> getLiveStockList() {
    return stockLiveData;
}

And then either

List stock = gson.fromJson(stringBuilder.toString(), new TypeToken<List<StockItem>>() { }.getType());
stockLiveData.postValue(stock);

or

stockLiveData.postValue(gson.fromJson(stringBuilder.toString(), new TypeToken<List<StockItem>>() { }.getType()))

You can also access the list inside LiveData like below:

stockLiveData.getValue();

Which return the original list data.

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • I have to manage the List items. Have to add, edit or remove them. What's more I can not loose the list f.e on Fragment rotation etc. What I mean is .getValue will create next temporary copy every time I need to change the List. It's almost the same impact as keeping the List all the time. As I assume your answer is - stockLiveData has to keep whole List, right? – Paul Paku Nov 12 '19 at 11:54
0

There are couple of things about your code I want to point out here:

  1. You do not necessarily need to call postValue in your getter function. As far as there are observers observing from your getter function, you can post value from anywhere.
  2. Even if you use mutable live data that does not necessarily mean that you're allocating memory for or creating a copy of List. When you set or post value on your Mutable Live Data, you're basically referencing the existing list on to value in your Mutable Live Data.
ked
  • 79
  • 5