分页库DataSource.Factory用于多个数据源 [英] Paging library DataSource.Factory for multiple data sources

查看:199
本文介绍了分页库DataSource.Factory用于多个数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的分页库使我们可以指定用于数据分页的自定义数据源。 github上的分页库文档和示例代码向我们展示了如何通过创建DataSource.Factory的子类来创建自定义数据源实例,例如:

The new paging library allows us to specify a custom data source to use with data pagination. Paging library documentation and sample code on github show us how to create your custom data source instances by creating a subclass of DataSource.Factory like so:

class ConcertTimeDataSourceFactory(private val concertStartTime: Date) :
    DataSource.Factory<Date, Concert>() {
    val sourceLiveData = MutableLiveData<ConcertTimeDataSource>()
    override fun create(): DataSource<Date, Concert> {
        val source = ConcertTimeDataSource(concertStartTime)
        sourceLiveData.postValue(source)
        return source
    }
}

在实际应用中,您通常会有带有recyclerviews的多个视图,因此有多个自定义数据源。因此,您最终会为每个数据源创建DataSource.Factory的多个实现还是还是有一个更通用的解决方案?

In a real app, you'd generally have multiple views with recyclerviews and hence multiple custom data sources. So, do you end up creating multiple implementations of DataSource.Factory per data source or is there a more generic solution?

推荐答案

我们可以创建包含多个LiveData对象的DataSource.Factory类的多个实例。

We can create multiple instances of DataSource.Factory class which holds multilpe LiveData objects.

首先在主活动中创建factory和viewmodel的实例,然后编写一个开关条件,否则为从DataSource.Factory类中选择数据源。

First create instance of factory and viewmodel in main activity then write a switch condition or if else ladder for choosing data source from DataSource.Factory class.

在切换条件下,您需要调用factory.create(viewmodel).getLiveData方法

In switch condition you need to call factory.create(viewmodel).getLiveData method

例如

switch (service){
        case 1:
            final Adapter adapter = new Adapter();
            factory.create(viewModel.getClass()).getPagedECListLiveData().observe((LifecycleOwner) activity, new Observer<PagedList<ECRecord>>() {
                @Override
                public void onChanged(@Nullable PagedList<ECRecord> ecRecords) {
                    Adapter.submitList(ecRecords);
                }
            });
            recyclerView.setAdapter(adapter);
            break;
        case 2:
            final CAdapter cadapter = new CAdapter();
            factory.create(viewModel.getClass()).getPagedSTListLiveData().observe((LifecycleOwner) activity, new Observer<PagedList<STRecord>>() {
                @Override
                public void onChanged(@Nullable PagedList<STRecord> stRecords) {
                    ECTAdapter.submitList(stRecords);
                }
            });
            recyclerView.setAdapter(cadapter);
            break;
}

快乐编码:)

这篇关于分页库DataSource.Factory用于多个数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆