android 如何每x秒更新一次值或当房间数据库中的值发生变化时更新值

jjjwad0x  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(114)

我希望变量listOfPoints在每次workout.points更改时或每“x”秒更改一次。

var listOfPoints = emptyList<LatLng>()

var workoutId = viewModel.getAllWorkouts().collectAsState(null).value?.size

if(workoutId != null) {
   var workout = viewModel.getSpecifWorkout(workoutId).collectAsState(null).value
   if (workout != null) {
       listOfPoints = viewModel.convertStringToListOfLatLng(workout.points)
   }
}

字符串
其余代码:https://github.com/DawidSiudeja/RunTracker/blob/main/app/src/main/java/com/example/runtracker/presentation/screens/active_workout/ActiveWorkout.kt

mcvgt66p

mcvgt66p1#

我假设上面的代码是可组合函数的一部分,如果是这样,你可以将if块 Package 在LaunchedEffect中,键为workout,如下所示:

var listOfPoints by remember { mutableStateOf(emptyList<LatLng>()) }

var workoutId = viewModel.getAllWorkouts().collectAsState(null).value?.size

var workout = if(workoutId != null) {
    viewModel.getSpecifWorkout(workoutId).collectAsState(null).value
} else {
    null
}

LaunchedEffect(workout) {
    listOfPoints = if (workout != null) {
        viewModel.convertStringToListOfLatLng(workout.points)
    } else {
        null
    }

}

字符串
这样,传递给LaunchedEffect的块将在每次workout更改时被调用,但不会在每次重组时被不必要地调用。
https://developer.android.com/jetpack/compose/side-effects#launchedeffect

相关问题