Skip to content

Instantly share code, notes, and snippets.

@mutkuensert
Created August 8, 2023 20:38
Show Gist options
  • Save mutkuensert/cfe28589da351df9b98db3086d1a148b to your computer and use it in GitHub Desktop.
Save mutkuensert/cfe28589da351df9b98db3086d1a148b to your computer and use it in GitHub Desktop.
Throws error if same request is done in 10 seconds.
private const val PREFS_SEQUENTIAL_REQUEST = "sequential-request-preferences"
private const val KEY_LAST_URL = "lastUrl"
private const val KEY_LAST_REQUEST_TIME = "lastRequestTime"
class SequentialRequestInterceptor(context: Context) : Interceptor {
private val preferences =
context.getSharedPreferences(PREFS_SEQUENTIAL_REQUEST, Context.MODE_PRIVATE)
override fun intercept(chain: Interceptor.Chain): Response {
val baseRequest = chain.request()
val lastUrl = preferences.getString(KEY_LAST_URL, null)
val lastRequestTime = preferences.getString(KEY_LAST_REQUEST_TIME, null)
return if (lastUrl != null
&& lastRequestTime != null
&& lastUrl == baseRequest.url.toString()
) {
if ((System.currentTimeMillis() - lastRequestTime.toLong()) > 10000) {
insertLastUrlAndRequestTime(baseRequest)
chain.proceed(baseRequest)
} else {
throw NetworkErrorException(
"Exact same sequential requests at a time shorter than 10 seconds. "
+ "\n Url: $lastUrl"
)
}
} else {
insertLastUrlAndRequestTime(baseRequest)
chain.proceed(baseRequest)
}
}
private fun insertLastUrlAndRequestTime(baseRequest: Request) {
preferences.edit {
putString(KEY_LAST_URL, baseRequest.url.toString())
putString(KEY_LAST_REQUEST_TIME, System.currentTimeMillis().toString())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment