Displaying the results

Now we need to have the UI perform the search and display the results. First, we need to add a search() function to be called when the button is clicked, and we also want to add the variables for the recycler view, the adapter, and the layout manager:

class SearchActivity : AppCompatActivity() 
{

private lateinit var articles: RecyclerView
private lateinit var viewAdapter: ArticleAdapter
private lateinit var viewManager: RecyclerView.LayoutManager

...

private suspend fun search() {
// TODO: Implement search function
}
}

To add the click listener, we just need to update the onCreate() function. Let's take this opportunity to also instantiate some of the added variables:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)

viewManager = LinearLayoutManager(this)
viewAdapter = ArticleAdapter()
articles = findViewById<RecyclerView>(R.id.articles).apply {
layoutManager = viewManager
adapter = viewAdapter
}

findViewById<Button>(R.id.searchButton).setOnClickListener {
viewAdapter.clear()
launch {
search()
}
}
}

Now, going back to the search() function of the activity, we need to retrieve the current text from the EditText, and then call Searcher.search(), passing that text as the query. To do that, let's add the searcher to the instance of our activity:

class SearchActivity : AppCompatActivity() 
{
private val searcher = Searcher()
...
}

Now we can perform the actual search and add the items to the adapter as they arrive:

private suspend fun search() {
val query = findViewById<EditText>(R.id.searchText)
.text.toString()

val channel = searcher.search(query)

while (!channel.isClosedForReceive) {
val article = channel.receive()

launch(UI) {
viewAdapter.add(article)
}
}
}

Now, whenever an article is found with the given query, the activity will receive it and add it to the adapter. Now you will be able to perform searches on all the feeds.

As an exercise, you can manually force delays in some of the feeds, and you will notice that as long as one of the feeds is fast, the experience of using the app will be acceptable.

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

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