As per the commentary of this answer, using CountDownTimer
val timer=object:CountDownTimer(Long.MAX_VALUE,10){
override fun onTick(p0: Long) {
_mutableLiveData.postValue(newValue)
}
override fun onFinish() {
TODO("Not yet implemented")
}
}.also { it.start() }
from inside a ViewModel
or otherwise would cause memory leaks. On the other hand implementing a timer using viewModelScope.launch
viewModelScope.launch {
while (true){
_mutableLiveData.postValue(newValue)
delay(10)
}
}
from inside the same ViewModel
wastes resources as a thread should exit after performing its task instead of going to sleep.
Which way should I use?
Is there some other idiomatic way that I am missing out?
The context of my question is this: in a ViewModel
, my timer implementation (currently using delay
) periodically changes the state of a private MutableLiveData
that is being observe
dAsState
in a @Composable