Skip to content

Commit 2259301

Browse files
Refactor: Consolidate withContext in isServerReachable
This commit refactors the `isServerReachable` function in `MainApplication.kt` to use a single `withContext(Dispatchers.IO)` block. This eliminates an unnecessary dispatcher switch and improves the code's efficiency. Additionally, a `try-finally` block has been introduced to ensure that the `HttpURLConnection` is always disconnected, even in the case of an exception.
1 parent 83a17ba commit 2259301

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

app/src/main/java/org/ole/planet/myplanet/MainApplication.kt

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -142,19 +142,19 @@ class MainApplication : Application(), Application.ActivityLifecycleCallbacks {
142142
}
143143

144144
val url = URL(formattedUrl)
145-
val connection = withContext(Dispatchers.IO) {
146-
url.openConnection()
147-
} as HttpURLConnection
148-
connection.requestMethod = "GET"
149-
connection.connectTimeout = 5000
150-
connection.readTimeout = 5000
151-
withContext(Dispatchers.IO) {
152-
connection.connect()
145+
val responseCode = withContext(Dispatchers.IO) {
146+
val connection = url.openConnection() as HttpURLConnection
147+
try {
148+
connection.requestMethod = "GET"
149+
connection.connectTimeout = 5000
150+
connection.readTimeout = 5000
151+
connection.connect()
152+
connection.responseCode
153+
} finally {
154+
connection.disconnect()
155+
}
153156
}
154-
val responseCode = connection.responseCode
155-
connection.disconnect()
156157
responseCode in 200..299
157-
158158
} catch (e: Exception) {
159159
e.printStackTrace()
160160
false

0 commit comments

Comments
 (0)