如何实现News API中top-headlines与everything文章的统一升降序排序?
实现News API两类文章的一键排序方案
问题背景
我需要点击一次就能对everything和top-headlines两类文章进行升序/降序排序,目前使用News API,现有接口定义如下:
@GET("top-headlines?sources=bbc-news&apiKey=${BuildConfig.API_KEY}") suspend fun getTopHeadlinesArticles( @Query("page") page:Int = 1 ) : Response<ArticleListResponse> @GET("everything?q=tesla&sortBy=publishedAt&apiKey=${BuildConfig.API_KEY}") suspend fun getAllArticles( @Query("page") page: Int = 1 ) : Response<ArticleListResponse>
遇到的问题是:sortBy参数只在everything接口生效,top-headlines接口用这个参数完全没效果(试过sortBy=publishedAt和-publishedAt)。根据API文档,top-headlines默认按最早发布日期排序,我需要让两类文章都能支持升序和降序切换。
文章的JSON结构示例(核心包含publishedAt字段):
"status": "ok", "totalResults": 37, "articles": [ { "source": { "id": "reuters", "name": "Reuters" }, "author": null, "title": "Russia says it resumes participation in Ukraine grain deal - Reuters.com", "description": "Russia said on Wednesday it would resume its participation in a deal to free up vital grain exports from war-torn Ukraine after suspending it over the weekend in a move that had threatened to exacerbate hunger across the world.", "url": "https://www.reuters.com/world/europe/grain-ships-sail-ukraine-ports-russian-missiles-knock-out-power-across-country-2022-10-31/", "urlToImage": "https://www.reuters.com/resizer/0q0d5ZOWPFOkR2Yc_Mbv8TQZrAA=/1200x628/smart/filters:quality(80)/cloudfront-us-east-2.images.arcpublishing.com/reuters/NQYU2CZKHRNKRDPQ76IQYOV2DE.jpg", "publishedAt": "2022-11-02T10:43:00Z", "content": "ANKARA/MYKOLAIV, Ukraine, Nov 2 (Reuters) - Russia said on Wednesday it would resume its participation in a deal to free up vital grain exports from war-torn Ukraine after suspending it over the week… [+2828 chars]" } ]
解决方案
1. everything接口:直接用API自带的排序能力
把现有getAllArticles方法修改一下,新增sortBy参数支持动态传入排序规则:
@GET("everything?q=tesla&apiKey=${BuildConfig.API_KEY}") suspend fun getAllArticles( @Query("page") page: Int = 1, @Query("sortBy") sortBy: String = "publishedAt" // 默认按发布时间降序 ) : Response<ArticleListResponse>
点击排序按钮时,切换传入的sortBy值即可:
- 降序(最新文章优先):传入
"publishedAt" - 升序(最早文章优先):传入
"-publishedAt"
2. top-headlines接口:本地排序(API不支持只能自己来)
因为News API的top-headlines接口不支持sortBy参数,所以只能在获取到数据后,本地基于publishedAt字段对文章列表排序。
首先可以定义一个枚举来管理排序状态,避免硬编码:
enum class SortOrder { ASC, // 升序:最早发布在前 DESC // 降序:最新发布在前 }
拿到top-headlines的响应数据后,根据当前排序状态处理列表:
// 假设response是接口返回的响应对象 val rawArticles = response.body()?.articles ?: emptyList() val sortedArticles = when(currentSortOrder) { SortOrder.ASC -> rawArticles.sortedBy { it.publishedAt } SortOrder.DESC -> rawArticles.sortedByDescending { it.publishedAt } } // 将sortedArticles用于UI展示
3. 一键切换排序的统一逻辑
在UI层维护一个全局的排序状态变量(比如currentSortOrder),点击排序按钮时执行以下步骤:
- 反转当前排序状态(
ASC切换为DESC,DESC切换为ASC) - 针对
everything页面:调用getAllArticles时传入对应的sortBy参数,重新请求接口更新UI - 针对
top-headlines页面:要么重新请求接口后对新数据排序,要么直接对本地已有的文章列表重新排序后更新UI
内容的提问来源于stack exchange,提问作者Equlo
相关产品推荐
相关产品推荐

