Skip to content

Instantly share code, notes, and snippets.

@llama-0
Created November 13, 2020 15:18
Show Gist options
  • Save llama-0/a2e252c7cc8b24fa6bcc1636dfc0fb77 to your computer and use it in GitHub Desktop.
Save llama-0/a2e252c7cc8b24fa6bcc1636dfc0fb77 to your computer and use it in GitHub Desktop.
/* a working example of Network Connectivity check for a small project without any modern architecture pattern used */
private var broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val notConnected = intent.getBooleanExtra(ConnectivityManager
.EXTRA_NO_CONNECTIVITY, false)
if (notConnected) {
showErrorLayout()
} else {
retryRequest()
}
}
}
override fun onResume() {
super.onResume()
registerReceiver(broadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
override fun onPause() {
super.onPause()
unregisterReceiver(broadcastReceiver)
}
private fun showErrorLayout() {
recycler_error_layout.visibility = View.VISIBLE
rv_items.visibility = View.GONE
}
private fun retryRequest() {
recycler_error_layout.visibility = View.GONE
rv_items.visibility = View.VISIBLE
refreshRecyclerViewData() // if this is a liveData observable used with ViewModel
// then network request will happen even if you press `home screen button`
// which kills the liveData + viewmodel approach (as I understand it)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment