Hey so I am trying to use the `androidx.lifecycle....
# android
a
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
@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
U didn't import
@Anas Tariq he is trying to use the ktx here to get rid of the exact Observer thing lol
t
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
aha it was indeed returning
Unit?
and not
Unit