How to implement timer (looping call) in Kotlin co...
# coroutines
j
How to implement timer (looping call) in Kotlin coroutine like
rxJava
Copy code
Single.timer(INTERVAL_SECONDS, TimeUnit.SECONDS)
      .flatMap{ // call API }
      .repeat()
      .subscribeOn(<http://Schedules.io|Schedules.io>())
I heard someone mentioned using
flow
. It look likes
Copy code
while(true){
    // call 
    // delay(intervalMili)
}
So I think it’s not looking good .
c
m
There's Ticker-channels, but the API is currently marked with "ObsoleteCoroutinesApi" because they're not integrated with structured concurrency. https://kotlinlang.org/docs/reference/coroutines/channels.html#ticker-channels
So the API will change in the future.
k
Copy code
fun buildTickerFlow(timeMillis: Long) = flow {
    while (true) {
        emit(Unit)
        delay(timeMillis)
    }
}

buildTickerFlow(1000).onEach { // do something }.launchIn(scope)
j
Ticker-channels ….hmmm
let me try
184 Views