I am using MutableStateFlow in my jetpack compose. Like below
val isBluetoothEnabled = MutableStateFlow(false)
whenever I tried to use the value of variable like this .value
i.e. isBluetoothEnabled.value
. So I am trying to use delegate property to avoid using .value
val isBluetoothEnabled by MutableStateFlow(false)
but I am getting weird error
Type 'MutableStateFlow<TypeVariable(T)>' has no method 'getValue(PairViewModel, KProperty<*>)' and thus it cannot serve as a delegate
CodePudding user response:
You should use this method
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()
}
CodePudding user response:
If you want to use it as a delegate in your Composable, you'll have to add .collectAsState()
to StateFlow
, otherwise Compose cannot detect state changes and therefore cannot update the value when necessary :)
Also if you only handle/update this value within the UI (and not a ViewModel for example), simply use mutableStateOf(false)