https://kotlinlang.org logo
Title
n

necati

07/02/2019, 5:48 PM
I need a way to do this in view model with coroutines.
Observable.interval(0, 1, TimeUnit.MINUTES)
When I leave the page, the task should be dismissed. Any suggestions?
l

louiscad

07/02/2019, 5:57 PM
A plain while loop with
delay
or
flow { emit(delay(60_000)) }
are ways to do this I guess.
j

Jag

07/03/2019, 3:50 AM
Just elaborating on Louis suggestion, maybe something like this could work? (and I’m assuming you’re looking for something that emits a monotonically increasing number starting from 0L spaced evenly as defined by the interval period)
fun <T> Flow<T>.interval(initialDelay: Long, period: Long, unit: TimeUnit = TimeUnit.MILLISECONDS) = flow {
    coroutineScope {
        delay(unit.toMillis(initialDelay))
        var value = 0L
        while (true) {
            emit(value++)
            delay(unit.toMillis(period))
        }
    }
}