[英]Jetpack Compose - Unresolved reference: observeAsState
I'm learning Jetpack Compose and I was trying to make a View Model for my @Composable.我正在学习 Jetpack Compose,我试图为我的 @Composable 创建一个 View Model。
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.在文档( https://developer.android.com/codelabs/jetpack-compose-state#3 )中用于观察
observeAsState
在他们使用的可组合方法中的变化,但在我的实现中找不到。 I get instead Unresolved reference: observeAsState
我得到了
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)
}
}
I am using Compose 1.0.0-beta01我正在使用 Compose 1.0.0-beta01
observeAsState
is part of the runtime-livedata
library. observeAsState
是runtime-livedata
库的一部分。
Add the dependency to your module's build.gradle
file.将依赖项添加到模块的
build.gradle
文件中。 Replace $compose_version
with the version of compose which you use, eg 1.0.0-beta01
:将
$compose_version
替换为您使用的 compose 版本,例如1.0.0-beta01
:
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
You can find the available versions here in Google's Maven repository .您可以在 Google 的 Maven 存储库中找到可用的版本。
Not exactly answering your question, but as a suggestion you could migrate to Flow instead of using live data.不完全回答您的问题,但作为建议,您可以迁移到 Flow 而不是使用实时数据。
ViewModel ->视图模型->
val yourList: MutableStateFlow<List<String>> = MutableStateFlow(listOf("String1","String2","String3"))
Composable ->可组合 ->
val yourList by yourViewModel.yourList.collectAsState()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.