Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the most 'lightweight' way to observe current time for a an android composable?

What would be the most lightweight way to observe current time from viewModel from a composable.

In my composable's view I would expect to see current time formatted as HH:mm and be always updated according to current time.

like image 722
F.Mysir Avatar asked Oct 24 '25 19:10

F.Mysir


1 Answers

You can use LaunchedEffect as in example below. I added seconds to show that it updates, you can change delay and formatting according to your needs.

@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)

    }
}

In ViewModel with 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)
            }
        }
    }
}

Usage

val currentTime = timeViewModel.timer.collectAsState()
Text(currentTime.value)

enter image description here

like image 171
Thracian Avatar answered Oct 27 '25 11:10

Thracian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!