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
Dominaezzz
07/21/2021, 2:07 PM
Atomic long should do I think. Unless you need some reactivity.
Dominaezzz
07/21/2021, 2:08 PM
Do you want to cancel and adjust the delay when the interval changes?
w
William Reed
07/21/2021, 2:08 PM
no - only adjust the next delay
William Reed
07/21/2021, 2:08 PM
so just having a
Box
like
AtomicLong
may work well
e
ephemient
07/21/2021, 3:56 PM
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.)