Having the adapter request more articles

We want to be able to request articles as the user scrolls, so the first step is to connect the adapter with the articles to a listener that can fetch more articles when needed. To do this, we are first going to add an interface to the same file where the class ArticleAdapter resides:

interface ArticleLoader {
suspend fun loadMore()
}

class ArticleAdapter: RecyclerView.Adapter<ArticleAdapter.ViewHolder>(){
...
}

This interface defines a suspending function that will load more articles if possible. Now we need to have the adapter receive an instance of that interface in the constructor, so that anyone using the adapter sends the proper listener. We will change the signature of the class to this:

class ArticleAdapter(
private val loader: ArticleLoader
): RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {
...
}

Now we need to add a flag so that the listener is not called more than it is necessary. Let's add a variable loading to the adapter. We can put it below the definition of the list of articles, like this:

private val articles: MutableList<Article> = mutableListOf()
private var loading = false

Finally, we have to update the function onBindViewHolder() so that it calls the listener when the binding of one of the elements close to the bottom happens:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val article = articles[position]

// request more articles when needed
if (!loading && position >= articles.size - 2) {
loading = true

launch {
loader.loadMore()
loading = false
}
}

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

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