I am new to kotlin and I am a little confused while using lambda expression in LiveData observe method.
The signature for observe method is as follows
observe(LifecycleOwner owner, Observer<? super T> observer)
where Observer is an interface with a single method
void onChanged (T t)
However,calling the above observe method in kotlin as follows gives type mismatch error :
val myViewModel = ViewModelProviders.of(this).get(AnimeListViewModel::class.java)
myViewModel.animes.observe(this, { anime -> println(anime) })
Isn't this the same as calling the setOnClickListener on a view. The following piece of code works perfectly without any compilation error:
val myView = View(this)
myView.setOnClickListener { view -> println(view) }
I have already read this answer which shows how to call the method using lambda expression (using SAM conversion). However, I am still not sure why a simple arrow expression would fail.
LiveData doesn't have a lambda expression, you should pass the observer interface as an object
myViewModel.animes.observe(this, Observer { anime -> println(anime) })
Or by creating an extension function like this
fun <T : Any> LiveData<T>.observe(lifecycleOwner: LifecycleOwner, block: (T) -> Unit) = observe(lifecycleOwner, Observer(block))
And calling it like this
myViewModel.animes.observe(this) { anime -> println(anime) }
Or like this
fun main() {
myViewModel.animes.observe(this, ::handleLiveData)
}
fun handleLiveData(anime: Anime) {
println(anime)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With