How to recompose every minute in Jetpack Compose?

Viewed 3119

I would like to show a timer counting down in my composable, but I am not sure how to achieve this.

I was thinking to set a delay/timeout for a minute and trigger a recompose that way, but I am not sure if that's the right way to think about it.

@Composable
fun Countdown(completedAt: Date) {
    val minutesLeft = ceil((completedAt.time - Date().time) / 60_000.0).toInt()

    Handler(Looper.getMainLooper()).postDelayed({
        // TODO: Recompose
    }, 60_000)

    Text(text = "$minutesLeft minutes until completed")
}

My goal is for the text to update every minute with the new time. How can I do this?

3 Answers

Store the amount of minutes as state.

Also make sure to clean up the postDelayed callback inside a DisposableEffect to prevent conflicting delays and memory leaks.

I have moved this logic to a minutesLeft composable function so it can be reused.

@Composable
fun minutesLeft(until: Date): Int {
    var value by remember { mutableStateOf(getMinutesLeft(until)) }

    DisposableEffect(Unit) {
        val handler = Handler(Looper.getMainLooper())

        val runnable = {
            value = getMinutesLeft(until)
        }

        handler.postDelayed(runnable, 60_000)

        onDispose {
            handler.removeCallbacks(runnable)
        }
    }

    return value
}

private fun getMinutesLeft(until: Date): Int {
    return ceil((until.time - Date().time) / 60_000.0).toInt()
}

Usage

@Composable
fun Countdown(completedAt: Date) {
    val minutes = minutesLeft(until = completedAt)

    Text(text = "$minutes minutes until completed")
}

You can use a ViewModel with the CountDownTimer class.

Something like:

 val countTimeViewModel : CountTimeViewModel = viewModel()
 val minutes  = countTimeViewModel.minutes.observeAsState(60)

  Button( onClick={ 
       countTimeViewModel.onStartClicked(60000*60) } 
  ){
        Text("Start")
  }

  Text(""+minutes.value)

with:

class CountTimeViewModel : ViewModel() {
    private var timer: CountDownTimer? = null

    private val _minutes = MutableLiveData(totalTime)
    val minutes: LiveData<Int> get() =  _minutes
   
    private var totalTime : Long = 0L

    fun startCountDown() {

        timer = object : CountDownTimer(totalTime, 60000) {
            override fun onTick(millisecs: Long) {

                // Minutes
                val minutes = (millisecs / MSECS_IN_SEC / SECS_IN_MINUTES % SECS_IN_MINUTES).toInt()
                _minutes.postValue(minutes)
            }

            override fun onFinish() {
               //...countdown completed

            }
        }

    }

    fun onStartClicked(totalTime : Long) {
        this.totalTime = totalTime
        startCountDown()
        timer?.start()
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
    }

    companion object {
        const val SECS_IN_MINUTES = 60
        const val MSECS_IN_SEC = 1000
    }
}
@Composable
fun minutesLeft(until: Date): Int {
    var timeout by remember { mutableStateOf(getMinutesLeft(until)) }

    Text(text = "$timeout minutes until completed")

    LaunchedEffect(timeout) {
        if (timeout > 0) {
            delay(1000 * 60)
            timeout -= 1
        }
    }
}

private fun getMinutesLeft(until: Date): Int {
    return ceil((until.time - Date().time) / 60_000.0).toInt()
}
Related