How to repeat a task within a duration of delay us...
# coroutines
a
How to repeat a task within a duration of delay using coroutines in Android?
i
while(!canceled) { delay(duration) doStuff() } ?
m
This keeps running until scope is cancelled
Copy code
launch {
        while (isActive) {
            delay(INTERVAL)
            doStuff()
        }
    }
a
@Marko Mitic is canceled or is not canceled? I am a little bit confused. I am not sure how to manage this method in the android UI thread.
m
it will keep running until scope is canceled, or while scope is not canceled (i hope that helps)
there are other ways of canceling the task if needed
about the UI thread, it's safe to run this on it, it will not block the UI (unless
doStuff()
takes a long time)
@Aslam Hossin does this help?
a
I want to do stuff repeatedly in an interval then Is it okay? I am working on it, Thanks for your input.
e
Copy code
withTimeoutOrNull(timeMillis){
        while(isActive){
            doThing()
        }
    }
or
Copy code
withTimeoutOrNull(timeMillis){
        while(true){
            doThing()
            yield()
        }
    }
m
That looks like it's gonna do the thing repeatedly for given time, not do it at an interval
e
isn't that what he is asking about? From his latest message:
I want to do stuff repeatedly in an interval
The wording of the question is a bit confusing
m
Yeah, it's not that clear. @Aslam Hossin Do you need task executed repeatedly for some time or once per time intrerval, repeatedly?
g
No need to check for cancellation or isActive if you have suspend function such as delay(), any suspend already checks cancellation on call and return
But nothing wrong to check isActive too