【问题标题】:Adding an object to a mutable live data list将对象添加到可变实时数据列表
【发布时间】:2020-12-25 01:11:26
【问题描述】:

我正在尝试将两个商店添加到一个可变列表中,如下所示:

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
    }

但是它说 add 函数没有被引用?

【问题讨论】:

    标签: android kotlin mutablelivedata


    【解决方案1】:

    来自文档:

    List:一个通用的有序元素集合。该接口中的方法只支持对列表的只读访问;通过 MutableList 接口支持读/写访问。

    MutableList:支持添加和删除元素的通用有序元素集合。

    您可以修改 MutableList:更改、删除、添加......它的元素。在列表中您只能阅读它们。

    解决方案-

     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
    }
    

    【讨论】:

    • 谢谢,请检查您的解决方案。我不认为您所指的更改已完成?
    • 它给出了两个错误。 1) 不可变 shopList 上的 get() 函数说存在类型不匹配。 2) add 函数仍然抛出错误?我们可能在这里遗漏了一些小东西,因为我明白你所说的背后的想法。
    • 一旦发现错误我会删除这些cmets
    【解决方案2】:

    解决办法如下:

    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
    }
    

    【讨论】:

    • 我已经通过更多优化更新了我的答案。请检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2013-09-03
    • 2012-08-02
    • 2015-12-16
    相关资源
    最近更新 更多