TASK
TASK

Reputation: 159

Android Studio/kotlin how to every 60 seconds run function

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

Upvotes: 0

Views: 728

Answers (1)

Tenfour04
Tenfour04

Reputation: 93581

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.

Upvotes: 1

Related Questions