1+ /*
2+ * Copyright (C) 2017 The Android Open Source Project
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+ package me.li2.android.common.arch
17+
18+ import android.os.SystemClock
19+ import androidx.collection.ArrayMap
20+ import java.util.concurrent.TimeUnit
21+
22+ /* *
23+ * Utility class that decides whether we should fetch some data or not.
24+ */
25+ class RateLimiter <KEY >(timeout : Int , timeUnit : TimeUnit ) {
26+ private val timestamps = ArrayMap <KEY , Long >()
27+ private val timeout: Long = timeUnit.toMillis(timeout.toLong())
28+
29+ @Synchronized
30+ fun shouldFetch (key : KEY ): Boolean {
31+ val lastFetched = timestamps[key]
32+ val now = now()
33+ if (lastFetched == null ) {
34+ timestamps[key] = now
35+ return true
36+ }
37+ if (now - lastFetched > timeout) {
38+ timestamps[key] = now
39+ return true
40+ }
41+ return false
42+ }
43+
44+ private fun now (): Long {
45+ return SystemClock .uptimeMillis()
46+ }
47+
48+ @Synchronized
49+ fun reset (key : KEY ) {
50+ timestamps.remove(key)
51+ }
52+ }
0 commit comments