Skip to content

Commit 25e9ec9

Browse files
fix(calendar): cancel blocking HTTP calls
1 parent 8fc9900 commit 25e9ec9

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

android/app/src/main/java/com/clhs/score/data/InterruptibleHttp.kt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package com.clhs.score.data
22

3+
import kotlinx.coroutines.CancellationException
34
import kotlinx.coroutines.Dispatchers
5+
import kotlinx.coroutines.Job
46
import kotlinx.coroutines.currentCoroutineContext
57
import kotlinx.coroutines.ensureActive
68
import kotlinx.coroutines.runInterruptible
9+
import okhttp3.Call
10+
import okhttp3.Response
711
import java.io.InterruptedIOException
812

913
internal suspend fun <T> runInterruptibleHttp(block: () -> T): T = try {
@@ -12,3 +16,14 @@ internal suspend fun <T> runInterruptibleHttp(block: () -> T): T = try {
1216
currentCoroutineContext().ensureActive()
1317
throw error
1418
}
19+
20+
internal suspend fun <T> Call.executeCancellable(block: (Response) -> T): T {
21+
val cancellation = currentCoroutineContext()[Job]?.invokeOnCompletion { cause ->
22+
if (cause is CancellationException) cancel()
23+
}
24+
return try {
25+
runInterruptibleHttp { execute().use(block) }
26+
} finally {
27+
cancellation?.dispose()
28+
}
29+
}

android/app/src/main/java/com/clhs/score/data/SchoolCalendar.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,17 @@ class NetworkSchoolCalendarRepository(
6060
readCache()
6161
}
6262

63-
suspend fun load(forceRefresh: Boolean): SchoolCalendarSnapshot = runInterruptibleHttp {
63+
suspend fun load(forceRefresh: Boolean): SchoolCalendarSnapshot {
6464
val now = nowProvider()
65-
val cached = readCache()
65+
val cached = runInterruptibleHttp { readCache() }
6666
if (!forceRefresh && cached != null &&
6767
Duration.between(cached.fetchedAt, now).let { !it.isNegative && it <= CACHE_MAX_AGE }
6868
) {
69-
return@runInterruptibleHttp cached
69+
return cached
7070
}
7171

7272
val request = Request.Builder().url(feedUrl).get().build()
73-
client.newCall(request).execute().use { response ->
73+
return client.newCall(request).executeCancellable { response ->
7474
if (!response.isSuccessful) {
7575
throw IOException("Calendar request failed with HTTP ${response.code}")
7676
}

0 commit comments

Comments
 (0)