1

我是分页库的新手,每当我使数据源无效时,分页会将列表带到顶部。我正在搜索他们所说的各种博客loadInitialloadRange应该从启动它的线程中调用,但在我的情况下,我在我的应用程序中使用协程,但我在不使用协程的情况下尝试了这种行为,一切正常。

数据源

class TestingDataSource(
    private val testingViewModel: TestingViewModel, private val coroutineScope: CoroutineScope
) : PositionalDataSource<TestingData>() {


    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<TestingData>
    ) {
        coroutineScope.launch {
            testingViewModel.testingData(0, params.requestedLoadSize) {
                callback.onResult(it, 0)

            }
        }
    }


    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<TestingData>) {
        coroutineScope.launch {
            testingViewModel.testingData(params.startPosition, params.loadSize) {
                callback.onResult(it)
            }
        }
    }

}

数据源工厂

class DataSourceFactory(
    private val testingViewModel: TestingViewModel,
    private val coroutineScope: CoroutineScope
) : DataSource.Factory<Int, TestingData>() {

    val dataSource: MutableLiveData<TestingDataSource> = MutableLiveData()

    override fun create(): DataSource<Int, TestingData> {
        return TestingDataSource(testingViewModel, coroutineScope)
            .also {
                dataSource.postValue(it)
            }
    }

    fun getDataSource(): TestingDataSource? {
        return dataSource.value
    }
}

视图模型

class TestingViewModel : ViewModel() {


    lateinit var dataSourceFactory: DataSourceFactory
    lateinit var dataList: LiveData<PagedList<TestingData>>

    var isInvalidate: Boolean = false

    val list = mutableListOf<TestingData>()


    fun dataSource() {

        dataSourceFactory = DataSourceFactory(this, viewModelScope)

        val config = PagedList.Config.Builder()
            .setPageSize(20)
            .setPrefetchDistance(5)
            .setEnablePlaceholders(false)
            .build()

        dataList = LivePagedListBuilder(dataSourceFactory, config)
            .build()
    }

    suspend fun testingData(offset: Int, limit: Int, callBack: suspend (List<TestingData>) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            if (isInvalidate) {
                callBack(list)
            } else {
                if (offset > 60) {
                    dataSourceFactory.getDataSource()?.invalidate()
                    isInvalidate = true
                } else {

                    val data = getData(offset)
                    list.addAll(data)
                    callBack(data)
                }
            }
        }
    }

    fun getData(offset: Int): List<TestingData> {
        return (offset..offset + 20).map {
            TestingData("Some_data_${it}", it.toString())
        }
    }

}

谁能建议我如何实现这一目标?

4

0 回答 0