hi guys - i have code that roughly looks like this...
# coroutines
w
hi guys - i have code that roughly looks like this were I poll on an endpoint until the result changes. My current code passes in the time interval as a parameter
Copy code
data class ApiResponse(
    val someId: Long,
    val success: Boolean,
)

suspend fun ApiResponse.poll(interval: Long) {
    var result = success
    while (!result) {
        result = sendSomeApiRequest(someId)
        delay(interval)
    }
}
A requirement I need to support is allowing users of this function to change the
interval
value while polling occurs based on outside information. would the most idiomatic way to do this be using a
StateFlow
? so my above function would become
Copy code
suspend fun ApiResponse.poll(interval: StateFlow<Long>)
d
Atomic long should do I think. Unless you need some reactivity.
Do you want to cancel and adjust the delay when the interval changes?
w
no - only adjust the next delay
so just having a
Box
like
AtomicLong
may work well
e
Copy code
suspend fun ApiResponse.poll(onRetry: suspend (ApiResponse) -> Unit) {
personally I'd probably do this - let the caller set up the delay, or whatever else is desired (print, counter, etc.)