G
G
genbachae2019-12-24 09:38:16
Android
genbachae, 2019-12-24 09:38:16

How to work with LiveData on Kotlin?

There is a Java code in which a subscription to LiveData is carried out and the "onChanged" function is called there without problems:
5e01b1a3a8c57686220056.png
And here is the code that does the same in Kotlin, but the "onChanged" function does not want to be called:
5e01b1c375722744281618.png
Please tell me where is the error?
Java project: Link1
Link2
Kotlin project: Link1
Link2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alina Mitrokhina, 2019-12-24
@genbachae

remove this ListView initialization line from the onChanged method. The method is needed only to update the data. This is how I do it myself

viewModel.getItems().observe(this, Observer { collections ->
            galleryRecycler.visibility = View.VISIBLE
            progressBarGallery.visibility = View.GONE
            galleryAdapter.setItems(collections.mapToGalleryItem())
        })

G
genbachae, 2019-12-25
@genbachae

Thank you very much! Replaced a piece of code:

RecsLiveData.observe(this, Observer<List<Rec>>() {
            fun onChanged(@Nullable Recs: List<Rec>) {
                val lvMain: ListView = findViewById(R.id.lvMain) as ListView // создаем адаптер
                recAdapter = RecAdapter(this@MainActivity, Recs)
                lvMain.setAdapter(recAdapter) // присваиваем адаптер списку
            }

to code:
RecsLiveData.observe(this, Observer<List<Rec>>() {
            val lvMain: ListView = findViewById(R.id.lvMain) as ListView    // создаем адаптер
            recAdapter = RecAdapter(this@MainActivity, it)
            lvMain.setAdapter(recAdapter)                                   // присваиваем адаптер списку
        })

and everything worked!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question