Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
} 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