https://kotlinlang.org logo
Title
p

Pablo

05/06/2021, 2:08 PM
How can I create a timer? I've done it like this
scope.launch{
 var foo = true
 while(foo){
 delay(1_000)
     //do some actions here
     //with these actions I check if the time is correct and if goes inside the if i put the foo to false so it leaves the while
     if(whatever) {
       foo=false
       //call one method here
     }
 }
}
Is this a correct way? Is there a better way with flow?
d

Derek Ellis

05/06/2021, 2:25 PM
If you're specifically looking for a way to do this as a flow, something like this would probably work:
flow {
  while (true) {
    emit(someValue)
    delay(1000)
  }
}.takeWhile { whatever }
p

Pablo

05/06/2021, 2:26 PM
I mean the way I did it correct without flow?
i'd like to avoid this while
g

gildor

05/06/2021, 2:37 PM
why do you want to avoid
while
?
p

Pablo

05/06/2021, 2:38 PM
I mean I'd like to listen another options, is this an optimal solution?
is flow doing some better things behind to replace this method I wrote it down?
g

gildor

05/06/2021, 2:40 PM
yes, it’s perfectly fine, I don’t see what makes you search for another solution
u

uli

05/07/2021, 6:10 AM
Is it a one shot timer and the idea is to poll every second, then fire once and exit? If so, why don't you set the delay to that time and get rid of the loop?