https://kotlinlang.org logo
Title
a

Aslam Hossin

08/09/2019, 4:40 PM
How to repeat a task within a duration of delay using coroutines in Android?
i

Ianmedeiros

08/09/2019, 4:42 PM
while(!canceled) { delay(duration) doStuff() } ?
m

Marko Mitic

08/09/2019, 4:44 PM
This keeps running until scope is cancelled
launch {
        while (isActive) {
            delay(INTERVAL)
            doStuff()
        }
    }
a

Aslam Hossin

08/09/2019, 4:46 PM
@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

Marko Mitic

08/09/2019, 4:54 PM
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

Aslam Hossin

08/09/2019, 5:00 PM
I want to do stuff repeatedly in an interval then Is it okay? I am working on it, Thanks for your input.
e

Eric Martori

08/09/2019, 8:33 PM
withTimeoutOrNull(timeMillis){
        while(isActive){
            doThing()
        }
    }
or
withTimeoutOrNull(timeMillis){
        while(true){
            doThing()
            yield()
        }
    }
m

Marko Mitic

08/09/2019, 8:45 PM
That looks like it's gonna do the thing repeatedly for given time, not do it at an interval
e

Eric Martori

08/09/2019, 8:50 PM
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

Marko Mitic

08/09/2019, 8:57 PM
Yeah, it's not that clear. @Aslam Hossin Do you need task executed repeatedly for some time or once per time intrerval, repeatedly?
g

gildor

08/10/2019, 2:05 AM
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