@@ -12,11 +12,11 @@ import androidx.core.content.edit
1212import androidx.core.net.toUri
1313import be.mygod.reactmap.App.Companion.app
1414import be.mygod.reactmap.util.headerLocation
15- import kotlinx.coroutines.CancellationException
1615import 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
2020import org.brotli.wrapper.enc.BrotliOutputStream
2121import org.brotli.wrapper.enc.Encoder
2222import timber.log.Timber
@@ -26,8 +26,6 @@ import java.net.HttpURLConnection
2626import java.net.URL
2727import java.util.zip.Deflater
2828import java.util.zip.DeflaterOutputStream
29- import kotlin.coroutines.resume
30- import kotlin.coroutines.resumeWithException
3129
3230object 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