Lyndon2309
Lyndon2309

Reputation: 49

Adding an object to a mutable live data list

I am trying to add two shops to a mutable list like so:

private var _shopList =  MutableLiveData<List<Shop>>()
    var shopList: LiveData<List<Shop>> = ()
        get() = _shopList


    // This function will get the arrayList items
    fun getArrayList(): MutableLiveData<List<Shop>>
    {


        // Here we need to get the data
        val shop1 = Shop("AOB", "Lat and Long","LA")
        val shop2 = Shop("Peach", "Lat and Long","Vegas")



        _shopList.add(shop1)
        _shopList.add(shop2)



        return _shopList
    }

However it says the add function is not referenced?

Upvotes: 1

Views: 1903

Answers (2)

Abhishek Dubey
Abhishek Dubey

Reputation: 945

From docs:

List: A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

MutableList: A generic ordered collection of elements that supports adding and removing elements.

You can modify a MutableList: change, remove, add... its elements. In a List you can only read them.

Solution -

 private var _shopList = MutableLiveData<List<Shop>>() // List is fine here as read only
val shopList: LiveData<List<Shop>>  // List is fine here as read only
    get() = _shopList


// This function will get the arrayList items
fun getArrayList(): MutableLiveData<List<Shop>> {
    // Here we need to get the data
    val shop1 = Shop("AOB", "Lat and Long", "LA")  //  var to val
    val shop2 = Shop("Peach", "Lat and Long", "Vegas") //var to val

    _shopList.value = mutableListOf(shop1, shop2) // assigns a mutable list as value to the live data which can be observed in the view

    return _shopList
}

Upvotes: 1

Lyndon2309
Lyndon2309

Reputation: 49

Here is the solution:

private var _shopList =  MutableLiveData<MutableList<Shop>>()
val shopList: LiveData<MutableList<Shop>> 
    get() = _shopList


// This function will get the arrayList items
fun getArrayList(): MutableLiveData<MutableList<Shop>>
{


    // Here we need to get the data
    var shop1 = Shop("AOB", "Lat and Long","LA")
    var shop2 = Shop("Peach", "Lat and Long","Vegas")


    _shopList.value = mutableListOf(shop1,shop2)

    return _shopList
}

Upvotes: 0

Related Questions