Trying out a few ways to throttle API GET requests. The `debounce`/`sample` operators for
Flow
don’t work as desired, so what I need is more of a
throttleFirst
. Tried with using
async
and returning
null
when the request should be throttled:
class ApiClient {
private var deferredLoad: Deferred<Result>? = null
suspend fun load(throttleMillis: Long = 300): Result? {
return coroutineScope {
if (deferredLoad?.isCompleted != false) {
async {
val result = /** make GET API call **/
delay(throttleMillis)
result
}
.apply { deferredLoad = this }
.await()
} else {
null
}
}
}
}
Is this approach recommended? Finding it a little weird to hold on to a
var
of
Deferred
, thinking it might need a
Mutex
. Wondering if there’s a more elegant approach that others have found?