最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

android - RecyclerView resets position after invalidate pagingSource - Stack Overflow

programmeradmin3浏览0评论

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:

发布评论

评论列表(0)

  1. 暂无评论