我希望在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
}