这是indexloc提供的服务,不要输入任何密码
Skip to content

Check internet connectivity, and handle network error when it's not available #39

@ryanw-mobile

Description

@ryanw-mobile

Right now we just let the API call proceed and populate the error from Retrofit.
It can end up with delays and piling up multiple error messages as it retrys.

There are multiple approaches to tackle this at the UI level or the ViewModel level.

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities

fun isNetworkAvailable(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetwork = connectivityManager.activeNetwork ?: return false
    val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
    return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}

OR

class ConnectivityObserver(context: Context) {
    private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    val networkAvailable: LiveData<Boolean> = MutableLiveData()

    init {
        val networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                (networkAvailable as MutableLiveData).postValue(true)
            }

            override fun onLost(network: Network) {
                (networkAvailable as MutableLiveData).postValue(false)
            }
        }

        connectivityManager.registerDefaultNetworkCallback(networkCallback)
    }
}

Then in the viewmodel

class MyViewModel(application: Application) : AndroidViewModel(application) {
    private val connectivityObserver = ConnectivityObserver(application)
    val isNetworkAvailable = connectivityObserver.networkAvailable

    fun fetchData() {
        if (isNetworkAvailable.value == true) {
            // Proceed with Retrofit call
        } else {
            // Handle lack of internet connectivity
        }
    }
}

Metadata

Metadata

Assignees

Labels

fixA bug fix for the user, not a fix to a build script.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions