Don't ignore the exception!

We have reached a nice point, at which our application will not crash when obtaining or processing the news from the feed, but there is something wrong here; currently, we are just putting the exceptions aside and not doing anything about them. For example, if you look at the preceding screenshot, for many users it will seem like there no news to fetch, not necessarily that fetching the information was not possible due to the phone being offline. In the case where one of the feeds' URLs was invalid, we made it look like the feed was processed along with the other three, and its news is part of the result.

Ignoring exceptions is bad practice, and we will ensure that we fix that. Let's add a label to our app, in which we will display the amount of feeds that the app failed to fetch. First, let's go to the XML of the activity and add a second label following the current one:

<TextView
android:id="@+id/warnings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@id/newsCount"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />

Now we need to go back to the activity and get a count of the feeds that completed exceptionally. Let's do that just after where we obtain the successful ones:

val headlines = requests
.filter { !it.isCancelled }
.flatMap { it.getCompleted() }

val failed = requests
.filter { it.isCancelled }
.size
At the time of writing, there is an effort from the Kotlin team to make the code above work as expected here. If you notice that  the list of failed requests is not being loaded correctly, please replace isCancelled with isCompletedExceptionally. I decided to avoid explaining isCompletedExceptionally because it's being deprecated close to the release of the book. For more information, please read issue 220 in the coroutines' Github repository.

We also need to obtain the View in order to be able to set the text. Let's do that below where we are currently obtaining the view with the summary. Also, let's add a convenience variable to hold the number of successful requests:

val newsCount = findViewById<TextView>(R.id.newsCount)
val warnings = findViewById<TextView>(R.id.warnings)
val obtained = requests.size - failed

Finally, we can now update the UI block to display more accurate information:

launch(UI) {
newsCount.text = "Found ${headlines.size} News " +
"in $obtained feeds"

if (failed > 0) {
warnings.text = "Failed to fetch $failed feeds"
}
}

Now we can display more accurate information to the user:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.0