LiveDataobserve() 没有被调用

问题描述 投票:0回答:1

Не понимаю,почему при добавлении элемента в список програмента в список програмента не считывает изменения и не вызввает метод 观察。

data class ListOfItems( var list:MutableList<Item> )
data class Item(
    var type:String,
    var date:String,
    var sum:Double
)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    findViewById<FloatingActionButton>(R.id.add_fab).setOnClickListener { view ->
        showMenu()
    }
    var resView = findViewById<RecyclerView>(R.id.ef_expenses_rv)
    resView.setHasFixedSize(true)
    val linearLayoutManager = LinearLayoutManager(this)
    linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
    resView.layoutManager = linearLayoutManager
    resView.adapter = adapter
    userViewModel.getList().observe(this,Observer {
            adapter.setItemsList(it.list)
    })
    }
class SecondClass: ViewModel() {
    var MyList:MutableLiveData<ListOfItems> = MutableLiveData()
    val mutableList1 = ListOfItems(mutableListOf())
    fun getItem(item: Item){
        mutableList1.list.add(item)
        MyList.value = mutableList1
        MyList.postValue(mutableList1)
        Log.d(" "," ")
    }
    fun getList() = MyList
}
Если смотреть относительно отладки он просто не доходит до того,что внутри блока 观察

kotlin mvvm android-recyclerview mutablelivedata
1个回答
0
投票
Ошибка была в том,что при добавлении данных,вместо уже использованное экземпляра viewModel,я создал отдельный и добавлял данный ые туда,потому-то 观察 и не вызывался

© www.soinside.com 2019 - 2024. All rights reserved.