File tree Expand file tree Collapse file tree
android/app/src/main/java/com/clhs/score/data Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com.clhs.score.data
22
3+ import kotlinx.coroutines.CancellationException
34import kotlinx.coroutines.Dispatchers
5+ import kotlinx.coroutines.Job
46import kotlinx.coroutines.currentCoroutineContext
57import kotlinx.coroutines.ensureActive
68import kotlinx.coroutines.runInterruptible
9+ import okhttp3.Call
10+ import okhttp3.Response
711import java.io.InterruptedIOException
812
913internal 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+ }
Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments