如何使用Paging 3处理许多Api请求



在这个代码实验室之后,我使用RemoteMediator实现了分页和缓存(我调用一个简单的API,它返回一个新闻列表(。我将这个RemoteMediator注入Repository,Repository具有返回Flow<PagingData<News>>的方法getResultStream()。在ViewModel中是函数getNews() : Flow<PagingData<News>>,在Fragment中我调用这个函数并将列表提交给RecyclerAdapter。

现在我想添加一个新的API调用,它返回新闻,但带有搜索关键字。做这件事的正确方法是什么?我必须重新编写所有这些代码并创建一个新的RemoteMediator吗?逻辑将是相同的,但现在我必须将一个字符串参数传递给Reform 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
}

NewsRemoteMedietor:

// 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
}
}
我不知道这是否是最好的方法(可能不是(,但在我的情况下,它是有效的

假设您还有一个回收视图,您可以执行以下操作:

val queryFlow = MutableStateFlow(startingQuery)
queryFlow.flatMapLatest { query ->
Pager(..., MyRemoteMediator(query)) {
MyPagingSource(...)
}.flow
}

最新更新