https://kotlinlang.org logo
#android
Title
# android
p

pdegand

05/30/2018, 10:17 PM
Hello, quick question about the SAM converter and live data : Why do I have to write
liveData.observe(this, Observer { })
when I can write
mediatorLiveData.addSource(liveData) {  }
? In both case, the 2d param of the
observe
or
addSource
is a
android.arch.lifecycle.Observer
and this interface has only 1 method ... I'm confused
1
l

louiscad

05/30/2018, 10:49 PM
I'm puzzled by this too, and ended up writing an extension in a library to get the nicer syntax: https://github.com/LouisCAD/Splitties/blob/master/arch-lifecycle/README.md#observe-and-observenotnull-extension-functions-on-lifecycleowner
r

russhwolf

05/31/2018, 3:20 AM
Just spitballing, but my guess is it's due to the difference in type parameters. In
MediatorLiveData.addSource
, both the source parameter and the lambda share a generic parameter, while in
LiveData.observe
the generic is only on the lambda. I'm guessing this means that the compiler can infer the generic type on the
MediatorLiveData
method but not the
LiveData
one, so you must use a syntax that specifies it.
The way I see it, kotlin compiler doesn't want to generate
2^n
variants for a method that has
n
parameters that are eligible for SAM conversion, so instead it generates only two variants: the one where all are lambdas and the one where there are no lambdas