Skip to content

Commit

Permalink
优化网络检测速度
Browse files Browse the repository at this point in the history
  • Loading branch information
aaa1115910 committed Jun 1, 2024
1 parent 1184107 commit 1354de4
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions app/src/main/kotlin/dev/aaa1115910/bv/util/NetworkUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext

object NetworkUtil {
Expand All @@ -32,7 +32,7 @@ object NetworkUtil {
}

suspend fun isMainlandChina() = withContext(Dispatchers.IO) {
locCheckUrls.map { locCheckUrl ->
val deferreds = locCheckUrls.map { locCheckUrl ->
async {
runCatching {
val result = client.get(locCheckUrl).bodyAsText()
Expand All @@ -47,6 +47,14 @@ object NetworkUtil {
false
}.getOrDefault(true)
}
}.awaitAll().all { it }
}

select {
deferreds.forEach { deferred ->
deferred.onAwait { it }
}
}.also {
deferreds.forEach { it.cancel() }
}
}
}

0 comments on commit 1354de4

Please sign in to comment.