Android Studio/kotlin how to every 60 seconds run function

Issue

I have next a fragment code:

@RequiresApi(Build.VERSION_CODES.O)
    fun get_date_to_new_year(): String {
        val CurrentDate = LocalDateTime.now()
        val needDateToNewYear = LocalDateTime.of(2023, 1, 1, 0, 0, 0)
        val DateToNewYear = Duration.between(CurrentDate, needDateToNewYear)
        return "До нового года " + (DateToNewYear.toDays()).toString()  + " дней\nили " +
                (DateToNewYear.toHours()).toString() + " часов\nили " + (DateToNewYear.toMinutes()).toString()  + " минут\nили " +
                (DateToNewYear.seconds).toString() + " секунд"
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private var _text = MutableLiveData<String>().apply {
        value = get_date_to_new_year()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    var text: LiveData<String> = _text

I need text variable to be updated every 60 seconds

Solution

If you move this to a ViewModel, it’s pretty easy using the liveData coroutine builder. No need for the MutableLiveData.

@RequiresApi(Build.VERSION_CODES.O)
val text: LiveData<String> = liveData {
    while(true) {
        emit(get_date_to_new_year())
        delay(60_000)
    }
}

If you don’t want to use a ViewModel, you could launch a coroutine in onViewCreated().

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    //..
    viewLifecycleOwner.lifecycleScope.launch {
        while(true) {
            _text.value = get_date_to_new_year()
            delay(60_000)
        }
    }
}

But if you’re not using a ViewModel, I think the LiveData is just an unnecessary extra layer. You could update your TextView or whatever directly in the coroutine.

Answered By – Tenfour04

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published