我使用ItemKeyedDataSource创建分页。并且对顶级电影getMovies()
进行了Api调用。但是在同一数据源中,我想对搜索getMovieForQuery("some movie")
进行api调用,但是由于某种原因,当我调用invalid时,我的查询被破坏了。这是代码:
class MovieDataSource(private val moveApi: ApiInterface,
private val compositeDisposable: CompositeDisposable)
: ItemKeyedDataSource<String, Movie>() {
private val movieType = "movie"
private var pageNumber = 1
private var query: String = ""
val loadState = MutableLiveData<DataLoadState>()
fun getMoviesForQuery(query: String) {
invalidate()
this.query = query
}
override fun loadInitial(params: LoadInitialParams<String>, callback: LoadInitialCallback<Movie>) {
loadState.postValue(DataLoadState.LOADING)
requestMovieList(params.requestedLoadSize, callback)
}
override fun loadAfter(params: LoadParams<String>, callback: LoadCallback<Movie>) {
loadState.postValue(DataLoadState.LOADING)
requestMovieList(params.requestedLoadSize, callback)
}
override fun loadBefore(params: LoadParams<String>, callback: LoadCallback<Movie>) {
}
override fun getKey(item: Movie): String = item.title
private fun requestMovieList(requestedLoadSize: Int, callback: LoadCallback<Movie>) {
loadState.postValue(DataLoadState.LOADING)
if (query == "") {
requestTopMovies(requestedLoadSize, callback)
} else {
requestMovieForQuery(requestedLoadSize, callback)
}
}
private fun requestTopMovies(requestedLoadSize: Int, callback: LoadCallback<Movie>) {
compositeDisposable.add(moveApi.getMovies(pageNumber++, requestedLoadSize).subscribe { movies ->
loadState.postValue(DataLoadState.LOADED)
callback.onResult(movies)
})
}
private fun requestMovieForQuery(requestedLoadSize: Int, callback: LoadCallback<Movie>) {
compositeDisposable.add(
moveApi.getMoviesForQuery(movieType, query, pageNumber++,
requestedLoadSize).subscribe({ movies ->
loadState.postValue(DataLoadState.LOADED)
val transformer = movies.map { generalMovieData -> generalMovieData.movie }.toList()
callback.onResult(transformer)
}, {
loadState.postValue(DataLoadState.FAILED)
}))
}
}
这是执行此操作的正确方法。