Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@andijakl
Created January 28, 2019 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andijakl/a0dc46df3c0c3163066ca6478709db80 to your computer and use it in GitHub Desktop.
Save andijakl/a0dc46df3c0c3163066ca6478709db80 to your computer and use it in GitHub Desktop.
Network request with additional try / catch to handle an IOException
private fun loadPartsAndUpdateList() {
GlobalScope.launch(Dispatchers.Main) {
try {
// Execute web request through coroutine call adapter & retrofit
val webResponse = WebAccess.partsApi.getPartsAsync().await()
if (webResponse.isSuccessful) {
// Get the returned & parsed JSON from the web response.
// Type specified explicitly here to make it clear that we already
// get parsed contents.
val partList: List<PartData>? = webResponse.body()
Log.d(tag, partList?.toString())
// Assign the list to the recycler view. If partsList is null,
// assign an empty list to the adapter.
adapter.partItemList = partList ?: listOf()
// Inform recycler view that data has changed.
// Makes sure the view re-renders itself
adapter.notifyDataSetChanged()
} else {
// Print error information to the console
Log.e(tag, "Error ${webResponse.code()}")
Toast.makeText(this@MainActivity, "Error ${webResponse.code()}", Toast.LENGTH_LONG).show()
}
} catch (e: IOException) {
// Error with network request
Log.e(tag, "Exception " + e.printStackTrace())
Toast.makeText(this@MainActivity, "Exception ${e.message}", Toast.LENGTH_LONG).show()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment