compose中遇到一个问题,界面无法及时更新对象的属性值,只有当重新进入该界面该值才会改变。我从viewmodel中传到compose中的对象是BluetoothGattService,通过StateFlow更新,在我的界面列表里有BluetoothGattCharacteristic的value值的显示,当value值改变时,界面无法自动更新。关键代码如下:
class ScanViewModel @Inject constructor(
private val bleManager: BLEManager,
application: Application
) : AndroidViewModel(application) {
...
val discoveredServices: Flow<List<BluetoothGattService>> = bleManager.discoveredServicesFlow
...
}
@Composable
fun ScanScreen(
navLogScreen: () -> Unit,
viewModel: ScanViewModel = hiltViewModel()
) {
...
val discoveredServices by viewModel.discoveredServices.collectAsState(initial = listOf())
...
}
@Composable
fun ServiceCardListColumn(
services: List<BluetoothGattService>,
) {
LazyColumn() {
services.forEach { service ->
item {
ServiceCard(service = service)
}
}
}
}
@Composable
fun ServiceCard(
service: BluetoothGattService,
) {
Box(modifier = modifier) {
...
Column {
service.characteristics.forEach {
...
characteristicCard(
it,
)
}
}
}
}
@Composable
fun characteristicCard(
characteristic: BluetoothGattCharacteristic,
) {
...
Text(text = characteristic.value?.toHexString()?:"")
}