简体   繁体   English

StateFlow.value 不应在组合内调用

[英]StateFlow.value should not be called within composition

I downloaded Android Studio Bumblebee beta today and noticed a new warning:我今天下载了 Android Studio Bumblebee 测试版并注意到一个新警告:

"StateFlow.value should not be called within composition" “不应在组合中调用 StateFlow.value”

Why shouldn't we call StateFlow.value within composition?为什么我们不应该在组合中调用 StateFlow.value?

Because in composition you should be listening to events, not just reading the current one.因为在作曲中,您应该聆听事件,而不仅仅是阅读当前事件。 If you read only the current one then your view won't get recomposed after the value is changed.如果您只阅读当前的,那么在更改值后您的视图将不会重新组合。

I mean - maybe there is a valid use case for that, but i never encountered one.我的意思是 - 也许有一个有效的用例,但我从未遇到过。 I guess the warning you saw is just to warn users that they are trying to do something they probably don't want to我想您看到的警告只是警告用户他们正在尝试做他们可能不想做的事情

In my case, I added .collectAsState() like this就我而言,我像这样添加了.collectAsState()

@Composable
fun yourScreen() {
    val state = viewModel.viewState.collectAsState()
    when (state.value) {
        // your code
    } 
}
   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM