如何在jetpack compose中使用MutableStateFlow中的delegate属性



我在我的jetpack撰写中使用MutableStateFlow。像下面的

val isBluetoothEnabled = MutableStateFlow(false)

每当我尝试使用变量的值,如.valueisBluetoothEnabled.value。所以我尝试使用委托属性来避免使用.value

val isBluetoothEnabled by MutableStateFlow(false)

但是我得到奇怪的错误

Type 'MutableStateFlow<TypeVariable(T)>' has no method 'getValue(PairViewModel, KProperty<*>)' and thus it cannot serve as a delegate

我认为如果你要使用委托方法,你应该使用var。

import androidx.compose.runtime.*
val isBluetoothEnabled by mutableStateOf(false)
private set

此私有集确保遵循单向数据流的原则。

然后在viewModel中不是写isBluetoothEnabled.value = true,而是写isBluetoothEnabled = true

你应该使用这个方法

import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class TestViewModel constructor(

) : ViewModel() {
private val _isBluetoothEnabled = MutableStateFlow(false)
val isBluetoothEnabled = _isBluetoothEnabled.asStateFlow()
}
@Composable
fun Sample1(
viewModel: TestViewModel 
) {
val isBluetoothEnabled = viewModel.isBluetoothEnabled.collectAsState()

}

如果你想在Composable中使用它作为委托,你必须将.collectAsState()添加到StateFlow,否则Compose无法检测状态变化,因此无法在必要时更新值:)

同样,如果你只在UI中处理/更新这个值(而不是ViewModel),只需使用mutableStateOf(false)

相关内容

  • 没有找到相关文章

最新更新