https://kotlinlang.org logo
Title
t

Tash

12/08/2020, 6:52 PM
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?
a

asad.awadia

12/08/2020, 7:41 PM
might be easier to throttle it at 3req/second instead of playing around with delays
💡 1