There is a RV where data is loaded page by page through a paging adapter, after pressing the refresh button I want to refresh the visible elements by loading the necessary pages from the API. For some reason, at some points the position in the RV gets lost. For example, this can be seen if you stand on element 2,10:50: CRS-13 and press refresh
MainActivity
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
private val launchesPagingAdapter: LaunchesPagingAdapter by lazy {
LaunchesPagingAdapter()
}
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
recyclerView = findViewById<RecyclerView>(R.id.rv_items).apply {
adapter = launchesPagingAdapter
}
findViewById<Button>(R.id.btn_refresh).apply {
setOnClickListener {
viewModel.refresh()
}
}
lifecycleScope.launch {
viewModel.launchesPagingData.collect { pagingData ->
launchesPagingAdapter.submitData(pagingData)
}
}
}
}
ViewModel
class MainViewModel : ViewModel() {
private var launchesPagingSource: LaunchesPagingSource? = null
get() {
if (field == null || field?.invalid == true) {
field = LaunchesPagingSource()
}
return field
}
val launchesPagingData = Pager(
PagingConfig(pageSize = 20, initialLoadSize = 20, prefetchDistance = 10)
) {
launchesPagingSource!!
}.flow
.cachedIn(viewModelScope)
fun refresh() {
launchesPagingSource?.invalidate()
}
}
How can I make the data of the necessary pages be refreshed?
My sample code is located here: