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

adams2

05/07/2020, 11:01 PM
Hey so I am trying to use the
androidx.lifecycle.observe
ktx extension. When I do
viewModel.observe(this, ::myOnChanged)
, I get this error:
Type mismatch: inferred type is KFunction1<Action, Unit?> but Observer<in Action!> was expected
. However, when I do
viewModel.observe(this) { myOnChanged(it) }
, the extension functions as expected. Is there some precedence rule preventing me from using a method reference?
a

Anas Tariq

05/08/2020, 6:08 AM
@adams2 the second parameter should be an Observer you can do something like.
Copy code
val observer = Observer<MyObject> { myObject -> 
  myOnChanged(myObject)
}

viewModel.observe(this, observer)
k

Kit

05/08/2020, 3:21 PM
U didn't import
@Anas Tariq he is trying to use the ktx here to get rid of the exact Observer thing lol
t

Travis

05/08/2020, 3:24 PM
Your
myOnChanged
fun is probably written as an expression that returns a nullable like
action?.let { /* do something */ }
so it's having trouble SAM converting to an Observer. Try either explicitly returning Unit from
myOnChanged
or just defining the function without the expression since you're trying to return Unit anyway.
a

adams2

05/11/2020, 4:19 PM
aha it was indeed returning
Unit?
and not
Unit