我希望在SoundViewModel类中设置_isRecording,并希望在UI中公开isRecording.

但是代码A是错误的,我该如何修复它?

Code A

    class SoundViewModel @Inject constructor(): ViewModel() {
    
        private var _isRecording by mutableStateOf(false)
        val isRecording: State<Boolean> by _isRecording  //It's wrong
        //val isRecording: State<Boolean> = _isRecording  //It's wrong
        ..
    }

Add content:

致劳伯:谢谢!

我认为代码B会很好用.

你的代码和代码B哪一个更好?

Code B

class SoundViewModel @Inject constructor(): ViewModel() {

   var isRecording by mutableStateOf(false)
              private set

}


@Composable
fun YourComposable(soundViewModel: SoundViewModel) {
   //I can use soundViewModel.isRecording directly
}

推荐答案

显然,代码B是最好的 Select .这正是官方文件的建议.LiveData个对象采用了带下划线的方法,但当您切换到Compose compatible MutableState<T>时,它只是在降低效率(?)你的代码,如果你添加了额外的下划线步骤.

查看State-in-Compose个完整的见解.

用最简单的方法完成工作,永远是经验法则.

Android相关问答推荐

Jetpack Compose:如何将浮动操作按钮上方的子按钮居中对齐?

Android可绘制边框删除底线

从我的 Android 应用程序发送到 Gin 时失败,但从 Postman 发送到 Gin 时成功

从 Jetpack Compose 中的图像中删除默认高度

expo 上的 socket.io 无法从 Android 连接

有没有办法让协程通道在接收时遵循特定的顺序而不是先进先出

是否可以在 Android 应用程序的 Wifi 设置中为 DNS 服务器设置自定义 IP?

在 kotlin 中动态添加 GridView

如何在一个活动中预加载图像然后在另一个活动中加载它们?

未解决的参考:pagerTabIndicatorOffset

Android工作室未成立

从活动共享视图模型以使用 hilt 组合函数

在 Jetpack Compose 中更改列中子项的对齐方式

如何从日期 Select 器计算年龄?

compose 更改列表元素但lazyColumn不更改

如何修复 api 调用在浏览器中工作但在 android studio 中为 403

如何使用 ConstraintLayout 链接两个文本

如何将房间数据库导出到 .CSV

在使用 Retrofit 和 Room 时,我是否需要提及协程调度程序?

Google API:java.lang.ClassNotFoundException:找不到类sun.misc.Service