How to Boost Your App’s Network Reliability: Ditching Network APIs for Exceptional Results
Every mobile development project involves layers of network interceptors and network connectivity APIs. Every time the app needs to consume a remote API, network availability must be checked first.
After working in Android for a significant amount of time, I’ve noticed that the network availability APIs in Android are not always very stable, and the results we obtain from them often do not meet our requirements. Let me provide some examples below:
if (networkConnection.available()){
val response = userRepository.login(username,password)
// handle response
}else {
// handle no network use-case
}
The snippet mentioned above is a common approach we use to handle network unavailability before executing any remote API.
Problems:
- Mobile devices may be connected to WiFi or mobile data networks, but internet access is not available through these channels.
- Users can disable network access for the app, which is possible on some Xiaomi phones.
- Internet access might be available when checking network conditions, but it may not be available when executing remote APIs.
Solutions:
We have implemented various solutions to address the above problems. One approach that has proven effective for all use cases is to avoid using network check APIs. Yes, you read that correctly — stop using network APIs to monitor network availability and start catching exceptions instead.
try {
val response = call.execute()
if (response.isSuccessful) {
println(response.body())
} else {
println("API call failed with code ${response.code()}")
}
} catch (e: IOException) {
println("Network error: ${e.message}")
} catch (e: Exception) {
println("An error occurred: ${e.message}")
}
Since this requires some boilerplate code in every API call, a better idea would be to create a base remote executor API with network exception handling. In the next article, I will explain how I eliminated this duplication.
Thanks for reading! :)