How to use Kotlin Flows to poll resource and emit it?

Viewed 2576

I want to make a nice logic for forever looping and emitting results with Kotlin Flows. The use case is that every n minutes I need to update a configuration in my app and this configuration comes from a rest api.

I thought a nice solution would be to run a "scheduler" that polls the api every n minutes in the background, and a ConfigService which is subscribed to this scheduler can update it's own state when the scheduler emits a new value.

Using RxJava this would be

Observable.interval(n, TimeUnit.MINUTES)
            .flatMap( ... )

But since I am using Kotlin I thought I could implement the same logic with the native Flow library. How would that look like? I was trying to google and either did not find the right keywords or just no one run into the same issue before?

1 Answers

Basically you use flow builder function, call suspending function to fetch the data and emit the result

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlin.time.minutes

flow<ApiResult> {
  while (true) {
    emit(fetchApi())
    delay(10.minutes)
  }
}

Be aware that this implementation is cold - i.e. it stops when it is not collected/observed.

It is possible that in the future there will be something like tickerFlow. The old ticker for channels (possibly converted to flow) is deprecated and definitely should not be used.

Related