https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

03/19/2024, 3:15 PM
i have an app that runs on a kiosk. I basically have this code, that works fine. BUT, in debug mode I can change the delayInterval. But when it changes, I have to wait for the original interval to hit, before the new interval is picked up. How would you go about "interupting" the delay()?
Copy code
//start reoccruing task on kiosk
    viewModelScope.launch {
      while (true) {
        delay(state.delayInterval)
        syncUseCase.sync()
      }
    }
fwiw, I'm assuming it would be saving a reference to this "job" and then cancelling it, and restarting it? Or maybe I shouldn't use my viewModelScope and just create a different one? Maybe another trick I'm missing?
s

Sam

03/19/2024, 3:22 PM
Put the
delayInterval
in a
StateFlow
and use
collectLatest
on it.
Copy code
val delayInterval = MutableStateFlow(someDelay)

viewModelScope.launch {
  delayInterval.collectLatest { interval ->
    while(true) {
      delay(interval)
      syncUseCase.sync()
    }
  }
}
☝️ 1
c

Colton Idle

03/19/2024, 3:23 PM
ooooh.
delayInterval is actually a compose snapshot state, so I think I can convert that using an extension method
instead of refactoring that type
cool
Copy code
snapshotFlow { state.delayInterval }.collectLatest { interval ->
will test that now!
ooooh yeah. THANK YOU @Sam
s

Sam

03/19/2024, 3:35 PM
🍻
j

Josh Eldridge

03/19/2024, 5:53 PM
That's awesome, thanks for sharing!
2 Views