73

I'm learning Jetpack Compose and I was trying to make a View Model for my @Composable.

In documentation (https://developer.android.com/codelabs/jetpack-compose-state#3) for observing state changes in composable they use observeAsState but in my implementation, the method cannot be found. I get instead Unresolved reference: observeAsState

ViewModel

class MainActivityViewModel : ViewModel() {
    val list: LiveData<MutableList<String>> = MutableLiveData(mutableListOf("Ana", "are", "mere"))

    fun addString(item: String) {
        val list: MutableList<String> = list.value!!
        list.add(item)
    }

}

Composable enter image description here

I am using Compose 1.0.0-beta01

Valentin
  • 1,159
  • 1
  • 11
  • 22
  • 3
    Just FYI if anyone reads this and doesn't follow: the original question from 2021 refers to the State Codelab v2021. In 2022 a new State Codelab was created and uploaded, so the url above doesn't take you to a place where you can see the code and this API anymore, but a page in the new codelab. Cheers! – Alejandra May 18 '22 at 22:09

3 Answers3

163

observeAsState is part of the runtime-livedata library.

Add the dependency to your module's build.gradle file. Replace $compose_version with the version of compose which you use, e.g. 1.0.0-beta01:

implementation "androidx.compose.runtime:runtime-livedata:$compose_version"

You can find the available versions here in Google's Maven repository.

Alexander Hoffmann
  • 5,104
  • 3
  • 17
  • 23
9

Not exactly answering your question, but as a suggestion you could migrate to Flow instead of using live data.

ViewModel ->

val yourList: MutableStateFlow<List<String>> = MutableStateFlow(listOf("String1","String2","String3"))

Composable ->

val yourList by yourViewModel.yourList.collectAsState()
mario chois
  • 116
  • 1
  • 2
0

CollectAsStateWithLifecycle is now recommended for Android by google devs and it's lifecycle api is also stable.Flow is also recommended by devs.

Premjit
  • 37
  • 8