Created
January 28, 2019 10:31
-
-
Save andijakl/a0dc46df3c0c3163066ca6478709db80 to your computer and use it in GitHub Desktop.
Network request with additional try / catch to handle an IOException
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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