How to Observe Internet Connectivity in Android — Modern Way with Kotlin Flow

Anubhav Sharma
3 min readSep 29, 2023

--

Hello! Dear Folks, Today I am going to talk about “How to Observe Internet Connectivity ? with Kotlin Flow”

Maintaining internet connectivity in your Android app is crucial for providing a seamless user experience. Whether your app relies on real-time data synchronization, streaming content, or server interactions, monitoring internet connectivity is a fundamental aspect of mobile app development. In this guide, we’ll explore how to observe internet connectivity in Android using Kotlin Flow, the modern and efficient way.

Why Monitor Internet Connectivity?

Observing internet connectivity in your Android app is essential for several reasons:

  1. User Experience: By detecting when the device goes offline, you can provide appropriate feedback to users, such as error messages or offline mode features, ensuring a smoother experience.
  2. Data Synchronization: For apps that rely on data synchronization, monitoring connectivity helps in scheduling sync operations when the device is online, avoiding unnecessary data usage and saving battery life.
  3. Efficient Network Usage: By knowing when the device is offline, you can avoid making unnecessary network requests, thus reducing data consumption and conserving battery power.

Using Kotlin Flow to Observe Internet Connectivity

In modern Android development, Kotlin Flow provides an elegant and reactive way to observe changes in internet connectivity. Here’s how to implement internet connectivity monitoring using Kotlin Flow:

1. Add Permissions

First, ensure your app has the necessary permissions to access the network state by adding the following lines to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2. Create a ConnectivityRepository

The ConnectivityRepository class is responsible for monitoring network connectivity and exposing it as a Flow:

import android.content.Context
import android.net.ConnectivityManager
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map

class ConnectivityRepository(context: Context) {

private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

private val _isConnected = MutableStateFlow(false)
val isConnected: Flow<Boolean> = _isConnected

init {
// Observe network connectivity changes
connectivityManager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
_isConnected.value = true
}

override fun onLost(network: android.net.Network) {
_isConnected.value = false
}
})
}
}

In this ConnectivityRepository:

  • We use the ConnectivityManager to access network-related information.
  • The _isConnected state variable is a MutableStateFlow that represents the current network connectivity status.
  • We register a network callback to monitor changes in connectivity. When the network becomes available or is lost, we update _isConnected accordingly.

3. Use the ConnectivityRepository in Your ViewModel

Next, use the ConnectivityRepository in your ViewModel to expose network connectivity changes as a Flow:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData

class MyViewModel(private val connectivityRepository: ConnectivityRepository) : ViewModel() {

val isOnline = connectivityRepository.isConnected.asLiveData()
}

Here, we expose the isOnline Flow as LiveData, making it easy to observe in the UI layer.

4. Observe Connectivity in Your UI with Kotlin Flow

Finally, in your UI layer (e.g., an Activity or Fragment), observe the internet connectivity status using Kotlin Flow:

class MyActivity : AppCompatActivity() {

private val viewModel: MyViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

viewModel.isOnline.observe(this) { isOnline ->
if (isOnline) {
// Handle online state
} else {
// Handle offline state
}
}
}
}

In this code:

  • We observe the isOnline Flow in the UI using LiveData, allowing us to respond to network connectivity changes efficiently.

Now, your Android app is equipped to monitor internet connectivity using Kotlin Flow. Whenever the device goes online or offline, your UI will react to the changes, ensuring a responsive and user-friendly experience.

Conclusion

Monitoring internet connectivity is a vital aspect of Android app development. With Kotlin Flow and the NetworkCallback API, you can easily observe network changes, adapt your app’s behavior, and provide a seamless experience for your users, regardless of whether they are online or offline. This modern approach to connectivity management helps ensure your app remains efficient and reliable in various network conditions.

--

--

Anubhav Sharma

I’m a software developer specialized in native Android app development with 5+ years of experience and worked with latest technologies in trend.