Home » Android » android – androidx ViewModel MutableLiveData LiveData-Exceptionshub

android – androidx ViewModel MutableLiveData LiveData-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I am new to Kotlin and Android programming. I cannot figure out why onChanged didnt show up in the first two examples but the last sample is ok. Any suggestions will be greater appreciated.

var liveDataTest:MutableLiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
var liveDataTest:LiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
class test:androidx.lifecycle.Observer<String>{
    override fun onChanged(t: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
How to&Answers:

In kotlin user can directly observe without implement override methods :

val liveDataTest: MutableLiveData<String> = MutableLiveData("ABC")
        liveDataTest.observe(this, androidx.lifecycle.Observer { it ->
            Toast.makeText(context,it,Toast.LENGTH_SHORT).show()
        })

Answer:

Your syntax is wrong in the first two. If you want to pass an anonymous class like that, the syntax is to use the object keyword, and since Observer is an interface, not a class, you don’t need to call its constructor with the ().

liveDataTest.observe(this, object: androidx.lifecycle.Observer {
    override fun onChanged(t: String?) {
        TODO("not implemented")
    }
})

But since this is single function Java-defined interface, you can simplify the syntax using a lambda:

liveDataTest.observe(this) {
    TODO("not implemented")
}