I'm working on an Android app where I have ViewMod...
# android
c
I'm working on an Android app where I have ViewModel arch component and I observe a liveData in my fragment. I want to have a countdown textView that counts from 50 to 0 and "ticks" every second. I plan on doing this by having this coroutine
Copy code
viewModelScope.launch {
            var initVal = 100
            repeat(100) {
                _myViewData.value =
                    _myViewData.value?.copy(initVal.toString())
                initVal--
                delay(1000)
            }
        }
Is there anything really bad with this approach? The only thing I can think of is how would the ViewModel being cleared would affect this.
a
probably easier to use a
for
loop, the VM being cleared will stop the countdown
also relevant is that you will be running even when the app is in the background, also time skew is possible if anything blocks the main thread handler for long enough
consider using the
liveData {}
builder
c
@Adam Powell 1. what would the conditions be inside the for loop? just the usual
int i = 0; ...
? 2. VM being cleared will stop the countdown? So it won't for
repeat()
?
a
for (value in 100 downTo 0)
VM being cleared cancels
viewModelScope
, so any
delay
call currently in progress will throw
CancellationException
c
@Adam Powell I basically just want a chronometer that counts down. lol I don't need any insane amount of accuracy, but def noted that if anything blocks main, it could skew. thanks for that tip.
@Adam Powell thanks for the advice. It works for my needs! Last thing though, what was the reasoning for swapping
repeat()
with
for(value...
a
just makes the code shorter đŸ™‚
c
Gotcha. I thought it was integral to cancellation/vm clearing
a
nah
g
I know that’s not what you asked, but you could handle the countdown in a custom view and just trigger it with the start value. (if it’s just a direct countdown to zero)
c
@Gonçalo Palaio custom views scare me đŸ˜ƒ
đŸ˜† 1