Skip to content

Commit 1913245

Browse files
committed
Avoid more GlobalScope
1 parent 535855e commit 1913245

1 file changed

Lines changed: 10 additions & 18 deletions

File tree

app/src/main/java/be/mygod/reactmap/webkit/ReactMapHttpEngine.kt

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ import androidx.core.content.edit
1212
import androidx.core.net.toUri
1313
import be.mygod.reactmap.App.Companion.app
1414
import be.mygod.reactmap.util.headerLocation
15-
import kotlinx.coroutines.CancellationException
1615
import kotlinx.coroutines.Dispatchers
17-
import kotlinx.coroutines.GlobalScope
18-
import kotlinx.coroutines.launch
19-
import kotlinx.coroutines.suspendCancellableCoroutine
16+
import kotlinx.coroutines.InternalCoroutinesApi
17+
import kotlinx.coroutines.coroutineScope
18+
import kotlinx.coroutines.job
19+
import kotlinx.coroutines.withContext
2020
import org.brotli.wrapper.enc.BrotliOutputStream
2121
import org.brotli.wrapper.enc.Encoder
2222
import timber.log.Timber
@@ -26,8 +26,6 @@ import java.net.HttpURLConnection
2626
import java.net.URL
2727
import java.util.zip.Deflater
2828
import java.util.zip.DeflaterOutputStream
29-
import kotlin.coroutines.resume
30-
import kotlin.coroutines.resumeWithException
3129

3230
object ReactMapHttpEngine {
3331
private const val KEY_COOKIE = "cookie.graphql"
@@ -76,18 +74,12 @@ object ReactMapHttpEngine {
7674
} else URL(url).openConnection()) as HttpURLConnection
7775
suspend fun <T> connectCancellable(url: String, block: suspend (HttpURLConnection) -> T): T {
7876
val conn = openConnection(url)
79-
return suspendCancellableCoroutine { cont ->
80-
val job = GlobalScope.launch(Dispatchers.IO) {
81-
try {
82-
cont.resume(block(conn))
83-
} catch (e: Throwable) {
84-
cont.resumeWithException(e)
85-
} finally {
86-
conn.disconnect()
87-
}
88-
}
89-
cont.invokeOnCancellation {
90-
job.cancel(it as? CancellationException)
77+
return coroutineScope {
78+
@OptIn(InternalCoroutinesApi::class) // https://github.com/Kotlin/kotlinx.coroutines/issues/4117
79+
coroutineContext.job.invokeOnCompletion(true) { conn.disconnect() }
80+
try {
81+
withContext(Dispatchers.IO) { block(conn) }
82+
} finally {
9183
conn.disconnect()
9284
}
9385
}

0 commit comments

Comments
 (0)