Creating an asynchronous function to hold the request... or not
Currently, a big part of our code to request and display the number of news is inside the onCreate()
function. This is less than optimal, not only because it's mixed with the creation of the activity, but also because it prevents reusing this code. For example, if there were to be a refresh button, we would need to reuse all the code of the coroutine.
When considering the separation of this coroutine into its own function, there are many possible approaches. Here, we will cover the most common ones.
A synchronous function wrapped in an asynchronous caller
The first approach is quite simple. We can create a loadNews()
function that directly invokes fetchRssHeadlines()
and displays its results in the same way we did before:
private fun loadNews(){ val headlines = fetchRssHeadlines() val newsCount = findViewById<TextView>(R.id.newsCount) launch(UI) { newsCount.text = "Found ${headlines.size} News" } }
Notice that this function...