Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use lambda arrow expression for Livedata observe method in Kotlin

Tags:

android

kotlin

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.

like image 678
Adityaraj Pednekar Avatar asked Jun 14 '19 21:06

Adityaraj Pednekar


1 Answers

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)
}
like image 194
Edy Daoud Avatar answered Nov 14 '22 23:11

Edy Daoud