Last active
December 8, 2025 18:39
-
-
Save mutkuensert/cfe28589da351df9b98db3086d1a148b to your computer and use it in GitHub Desktop.
Throws error if same request is done in 10 seconds.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private const val PREFS_REQUEST_RATE_LIMITER = "request-rate-preferences" | |
| private const val KEY_LAST_URL = "lastUrl" | |
| private const val KEY_LAST_REQUEST_TIME = "lastRequestTime" | |
| class RequestRateLimiterInterceptor(context: Context) : Interceptor { | |
| private val preferences = | |
| context.getSharedPreferences(PREFS_REQUEST_RATE_LIMITER, 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