F.M*_*sir 3 android kotlin kotlin-coroutines android-jetpack-compose
lightweight
从可组合项的 viewModel 观察当前时间的最有效方法是什么。
在我的可组合项看来,我希望看到当前时间的格式为HH:mm
并始终根据当前时间进行更新。
Thr*_*ian 10
您可以使用 LaunchedEffect,如下例所示。我添加了几秒钟来显示它已更新,您可以根据需要更改延迟和格式。
@Composable
private fun Timer() {
var time by remember { mutableStateOf("") }
val sdf = remember { SimpleDateFormat("HH:mm:ss", java.util.Locale.ROOT)}
LaunchedEffect(key1 = Unit){
while(isActive){
time = sdf.format(Date())
delay(1000)
}
}
Column(modifier=Modifier.fillMaxSize()) {
Text(time, fontSize = 40.sp)
}
}
Run Code Online (Sandbox Code Playgroud)
在 ViewModel 中MutableStateFlow
class TimerModel(private val dateFormat: SimpleDateFormat) : ViewModel() {
private val _timer = MutableStateFlow<String>(dateFormat.format(Date()))
val timer: StateFlow<String> = _timer
init {
viewModelScope.launch {
while (isActive) {
_timer.value = dateFormat.format(Date())
delay(1000)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法
val currentTime = timeViewModel.timer.collectAsState()
Text(currentTime.value)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
829 次 |
最近记录: |