Where is the best place to check for internet connection in MVVM?

Viewed 4159

I have an apiClass which makes all the network calls and I was thinking my options are these:

  1. do the check inside the activity/fragment

  2. do the check inside the apiClient class

I'm sure there is a better alternative.

EDIT

This answer suggests my second option. Is there a better approach?

3 Answers

create class connectivity manager in livedata

class Connectivity_check_internet(val context: Context) : LiveData<Boolean>() {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    var Connnectserver: Boolean? = false
    val reciveconnctivitymanager = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            Connnectserver=false
            UnpdateConnection()
            postValue(Connnectserver)
        }
    }
    init {
        UnpdateConnection()
    }

    fun UnpdateConnection(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
            capabilities?.run {
                Connnectserver=capabilities!!.hasTransport(TRANSPORT_CELLULAR) || capabilities.hasTransport(TRANSPORT_WIFI)
            }
        } else {
            try {
                val activeNetworkInfo = connectivityManager.activeNetworkInfo
                Connnectserver = activeNetworkInfo != null && activeNetworkInfo.isConnected
            } catch (e: Exception) {
            }
        }
    }

    override fun onActive() {
        super.onActive()
        context.registerReceiver(
            reciveconnctivitymanager,
            IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
        )
    }

    override fun onInactive() {
        super.onInactive()
        context.unregisterReceiver(reciveconnctivitymanager)
    }
}

class MainActivity : AppCompatActivity() { val Connectivity_internet by lazy { Connectivity_check_internet(this) }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    Connectivity_internet.observe(this,{
        Log.e("TAG", "onCreate: "+it )
    })

}

}

I think we should avoid using Context in ViewModel and data layer as much as possible. Therefore, the best place to check the Internet is where we have access to the Context, for example, in Activity or Fragment.

Related