android - 如何使用 Paging 3 处理许多 Api 请求
问题描述
在这个代码实验室之后,我使用RemoteMediator
(我正在调用一个返回新闻列表的简单 API)实现了分页和缓存。我将其注入到具有返回RemoteMediator
方法的存储库中。在 ViewModel 中是函数,在 Fragment 中我调用此函数并将列表提交给 RecyclerAdapter。getResultStream()
Flow<PagingData<News>>
getNews() : Flow<PagingData<News>>
现在我想添加一个返回新闻但带有搜索关键字的新 API 调用。正确的方法是什么?我是否必须再次编写所有这些代码并创建一个新的RemoteMediator
?逻辑将是相同的,但现在我必须将字符串参数传递给 Retrofit get 函数。此调用的结果将替换 RecyclerView 中的项目,因此我将有两个数据源但一个 Recycler,我是否还必须创建一个MediatorLiveData
?(我没有添加任何代码,但如果有帮助,我可以做到)
一个人问我到底是怎么做到的(问题已作为答案发布,因此现在已删除,但将来可能会对某人有所帮助)。所以,在 ViewModel 我有这个:
// this flow keeps query. If it is null it means that I want to get all News from API. If it is not null it means that I want to make another API request which takes a parameter query
private val _queryFlow: MutableStateFlow<String?> = MutableStateFlow(null)
val queryFlow: StateFlow<String?>
get() = _queryFlow
// this function set and validate query
fun submitQuery(query: String?)
{
Timber.d("Submit new search $query")
_queryFlow.value = when
{
query.isNullOrEmpty() -> null
query.trim()
.isNotBlank() -> query.trim()
else -> null
}
}
// flow of paging data that I am using in RecyclerView
@ExperimentalCoroutinesApi
val homeNewsData = _queryFlow.flatMapLatest {
searchNews(it)
}
private fun searchNews(
query: String?
): Flow<PagingData<NewsRecyclerModel>>
{
return newsRepository.getSearchResultStream(
query
)
// mapping, filtering, separators etc.
.cachedIn(viewModelScope)
}
NewsRepository 在 VM 中使用了这个函数:
fun getSearchResultStream(searchKey: String?): Flow<PagingData<News>>
{
val pagingSourceFactory = { database.cacheNewsDao.getNews() }
return Pager(
config = PagingConfig(
pageSize = NETWORK_PAGE_SIZE,
enablePlaceholders = false,
initialLoadSize = INITIAL_LOAD_SIZE
),
remoteMediator = newsRemoteMediator.apply { this.searchKey = searchKey },
pagingSourceFactory = pagingSourceFactory
).flow
}
新闻远程调解员:
// it keeps submitted query. based on this I can letter define which API request I want to do
var searchKey: String? = null
override suspend fun load(loadType: LoadType, state: PagingState<Int, News>): MediatorResult
{
\\ all logic the same like in codelabs
try
{
val apiResponse =
if (searchKey.isNullOrEmpty()) // query is null/empty get Trending news
newsRetrofit.getTrending(
state.config.pageSize,
page * state.config.pageSize
)
else // query is not blank, make API request with search keyword
newsRetrofit.getSearched(
state.config.pageSize,
page * state.config.pageSize,
searchKey!!
)
\\ again the same logic like in codelabs
}
}
我不知道这是否是最好的方法(可能不是),但就我而言,它正在工作
解决方案
假设您仍然有一个 recyclerview,您可以执行以下操作:
val queryFlow = MutableStateFlow(startingQuery)
queryFlow.flatMapLatest { query ->
Pager(..., MyRemoteMediator(query)) {
MyPagingSource(...)
}.flow
}
推荐阅读
- reactjs - 如何解决在 Ubuntu 18.04 安装 reactjs 时出现的错误
- python-3.x - 将csv文件转换为字典
- javascript - 调用函数前如何使div清晰?
- c# - 如何在不更改其他视图 URL 的情况下为视图添加到 mvc 的路由?
- java - Esper引擎:我不能在'inner join on'之后使用'<'或'>'吗?
- spring-boot - 在 Intellij IDEA 中将 vaadin 添加到 Spring Boot 项目时出错
- mysql - 错误:命令'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.25.28610\\bin\\HostX86\\x86\\cl 。可执行程序'
- javascript - 有人可以解释为什么我需要在 2 个不同的函数中使用 await 来获取 json 吗?
- python - AttributeError:'int'对象在抓取维基百科时没有属性'parent'
- java - Pojo验证的Spring Boot Pojo不起作用