Home > Back-end >  What would be the most 'lightweight' way to observe current time for a an android composab
What would be the most 'lightweight' way to observe current time for a an android composab

Time:08-12

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.

CodePudding user response:

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

  • Related