Fix: Jetpack Compose observeAsState Type Error has no method

This quick blog post helps you solve the error “Type state has no method getValue” when first starting to observe state on your ViewModel.

With Jetpack Compose being a new technology there are going to be lumps and bumps, especially with tooling. This quick blog post helps you solve the error “Type state has no method getValue” when first starting to observe state on your ViewModel.

If you follow the example code in the official documentation for ViewModel state, you’ll end up creating some code like this:

class HelloViewModel : ViewModel() {
    private val _name = MutableLiveData("")
    val name: LiveData<String> = _name
}

@Composable
fun HelloScreen(helloViewModel: HelloViewModel = viewModel()) {
    // name is the current value of [helloViewModel.name]
    // with an initial value of ""
    val name: String by helloViewModel.name.observeAsState("")
    // etc
}

The first error’s you’ll get will involve missing dependencies, easily fixed with adding them (pls ensure you use the latest versions, this snippet will go out of date):

implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02"

But then the most confusing error occurs:

Type ‘State’ has no method ‘getValue(Nothing?, KProperty<*>)’ and thus it cannot serve as a delegate

It really doesn’t have an obvious solution (and thank you Florina for pointing it out to me!). This is where the tooling has not caught up with the coding. The IDE cannot offer you a quick fix.

You need to import the getValue method so it can be used:

import androidx.compose.runtime.getValue

Your imports may differ, but notice the highlighted blue newly (manually) added import for getValue:

That’s it! The red compile squiggles goes away and you can carry on with Jetpack Compose, ViewModel’s and observing state.

Enjoy!

One thought on “Fix: Jetpack Compose observeAsState Type Error has no method

Comments are closed.