mapByPage和PageKeyedDataSource ClassCastException

时间:2019-05-02 18:38:37

标签: android android-architecture-components android-paging

我的问题是使用mapByPage时如何使用PageKeyedDataSource。目前我正在

java.lang.ClassCastException: androidx.paging.DataSource$Factory$1 cannot
be cast to com.exmple.paging.MyDataSource$Factory
// ...

所以从DataSource开始,它是Factory:

class MyDataSource private constructor(
      private val query: Query
) : PageKeyedDataSource<Query, Message>() {

    // Here I'm trying to get the loading states while each method of DataSource
    // is doing the work
    private val _loadState = MutableLiveData<LoadingState>()
    val loadState: LiveData<LoadingState>
        get() = loadState

   override fun loadInitial(params: LoadInitialParams<Query>,
                             callback: LoadInitialCallback<Query, Message>) {
        // Getting loading states for UI
        loadStateMld.value = NetworkState.loading() 

        doWork()
    }

    override fun loadAfter(params: LoadParams<Query>,
                           callback: LoadCallback<Query, Message>) {
        loadStateMld.value = NetworkState.loading()

        doMoreWork()
    }

    // ...

    // The factory
    class Factory private constructor(
            private val query: Query
    ) : DataSource.Factory<Query, Message>() {

        private val _sourceMld = MutableLiveData<MyDataSource>()
        val sourceLd: LiveData<MyDataSource>
            get() = _sourceMld

        override fun create(): DataSource<Query, Message> {
            val itemKeyedDataSource = MyDataSource(query)
            _sourceMld.postValue(itemKeyedDataSource)
            return itemKeyedDataSource
        }
    }
}

在ViewModel中,我在下一行得到了错误

val liveData = Transformations.switchMap(userName) { name ->
    val query: Query = messageColRefQuery.whereArrayContains("name", name)

    val factory = MessageDataSource.Factory(
            query
    ).mapByPage {
        // will be doing some work here
        it
    }

    LivePagedListBuilder(factory, config).build()
}

// Getting loading states to display on UI
private val loadState = Transformations.switchMap(liveData) { input ->
    // This line is causing the error
    val dataSource = input.dataSource as MyDataSource 
    dataSource.loadStateLd
}

问题是,链接mapByPage返回DataSource.Factory<Query, Message>,而链接返回MyDataSource.Factory。因此,结果是,当我尝试从数据源获取loadState LiveData时,由于未将其强制转换为正确的类而导致了错误。

如果我尝试投射链接,它也会失败:

val factory = MessageDataSource.Factory(query).mapByPage { it } as MyDataSource.Factory

不使用map函数,一切正常。任何帮助表示赞赏。

0 个答案:

没有答案