Handling Internet Connections
Learn how to handle the loss of internet connections.
We'll cover the following
Why handle internet connections?
Most Android applications fetch data remotely from APIs, and to do that efficiently, our device needs to be connected to an active network.
We, as developers, must inform the user when an internet connection is required to load data. To do that, we must develop a mechanism to simply detect if the device is connected to an active internet connection source.This can be mobile data or a WiFi connection.
In other instances, an application can just crash if it’s meant to make use of the internet and the device is not connected. This is a case where the developer hasn’t handled internet connection issues. In this lesson, we’ll learn how to handle internet connections in our Android programs.
Making changes to the ViewModel
Views are only used to present data. UI-related logic is handled by the ViewModel. We’ll make a few changes to the NewsViewModel
to accommodate the logic that handles internet connectivity.
Let’s get into it!
Instead of NewsViewModel
extending the ViewModel class, we’ll extend the AndroidViewModel
. The difference between the two is that the AndroidViewModel
will allow us to use context in our logic, while ViewModel doesn’t permit the use of context in its class. This marks the beginning of the refactoring process.
Code refactoring is a process of improving our code by restructuring it in a way that doesn’t affect its external behavior. The goal is just to improve its internal code. Below is the extension.
Get hands-on with 1400+ tech skills courses.