title: Android RecyclerView backed by list that is constantly changing in size
body: <p>I have a <code>RecyclerView</code> which displays a <code>List</code> of paginated elements. 
  Initially the size of the list will be <code>n</code>, but as you approach the top, more elements need to be loaded, and the adapter will fetch <code>p</code> elements ( and the list will grow to a size of <code>n + p</code>)</p>
  
  <p>The way I am doing this is fetch <code>p</code> elements and prepend it to the list inside <code>onBindViewHolder</code> if <code>position</code> is 0:</p>
  
  <pre><code>class MyAdapter : RecyclerView.Adapter&lt;MyViewHolder&gt;() {
      val elements: List&lt;Any&gt; = emptyList()
  
      override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
          //viewholder binding code
          if (position == 0) {
              loadPreviousPage()
          } 
      }
  
      private fun loadPreviousPage() {
          val newElements = someCall() //List of size p
          elements.addAll(0, newElements)
      }
  }
  </code></pre>
  
  <p>This works fine for the most part. Here's the problem:</p>
  
  <p>Suppose there are <code>3p</code> total elements (3 pages) that can be fetched, meaning the adapter starts off with <code>0</code> elements, then <code>loadPreviousPage</code> is called, and <code>elements</code> grows to <code>p</code>, <code>2p</code> and finally <code>3p</code>. What I'm seeing is that the list is getting updated, but the <code>View</code>s aren't.</p>
  
  <p>Example:</p>
  
  <p>If <code>p = 3</code>, my <code>elements</code>, per pagination call, looks like:</p>
  
  <pre><code>I   : g h i
  II  : d e f g h i
  III : a b c d e f g h i
  </code></pre>
  
  <p>But in my <code>RecyclerView</code>, I see something like <code>i d e d e f g h i</code></p>
  
  <p>If I scroll so that the incorrect <code>View</code>s go out of the screen and scroll back, everything is fine and the <code>RecyclerView</code> looks as expected (<code>a b c d e f g h i</code>)</p>
  
  <p>I am not sure exactly what is happening, but this behaviour (and even state of the <code>RecyclerView</code>) is consistent and reproducible. I suspect that since the list size is changing, an element that used to be in position <code>m</code> is no longer at the same position after adding <code>p</code> elements to it, and the <code>RecyclerView</code> has not been notified of this. However, I cannot call <code>notiyItemChanged</code> in <code>loadPreviousPage</code> because it is being called from <code>onBindViewHolder</code>, at the time of layout itself.</p>
  
  <p>How can I solve this problem? Any help would be appreciated.</p>