【发布时间】:2017-05-20 18:41:42
【问题描述】:
我正在使用 Spotify API,并希望使用 RxJava 链接一些分页结果。 Spotify 使用基于光标的分页,因此the one from @lopar 之类的解决方案将不起作用。
回复来自this call,看起来像这样(假设有50个items):
{
"artists" : {
"items" : [ {
"id" : "6liAMWkVf5LH7YR9yfFy1Y",
"name" : "Portishead",
"type" : "artist"
}],
"next" : "https://api.spotify.com/v1/me/following?type=artist&after=6liAMWkVf5LH7YR9yfFy1Y&limit=50",
"total" : 119,
"cursors" : {
"after" : "6liAMWkVf5LH7YR9yfFy1Y"
},
"limit" : 50,
"href" : "https://api.spotify.com/v1/me/following?type=artist&limit=50"
}
}
现在,我正在使用改造获得前 50 个这样的结果:
public class CursorPager<T> {
public String href;
public List<T> items;
public int limit;
public String next;
public Cursor cursors;
public int total;
public CursorPager() {
}
}
public class ArtistsCursorPager {
public CursorPager<Artist> artists;
public ArtistsCursorPager() {
}
}
然后
public interface SpotifyService {
@GET("/me/following?type=artist")
Observable<ArtistsCursorPager> getFollowedArtists(@Query("limit") int limit);
@GET("/me/following?type=artist")
Observable<ArtistsCursorPager> getFollowedArtists(@Query("limit") int limit, @Query("after") String spotifyId);
}
和
mSpotifyService.getFollowedArtists(50)
.flatMap(result -> Observable.from(result.artists.items))
.flatMap(this::responseToArtist)
.sorted()
.toList()
.subscribe(new Subscriber<List<Artist>>() {
@Override
public void onNext(List<Artist> artists) {
callback.onSuccess(artists);
}
// ...
});
我想返回callback.success(List<Artist>) 中的所有(在本例中为 119 位)艺术家。我是 RxJava 新手,所以我不确定是否有 智能 方法可以做到这一点。
【问题讨论】:
-
在拨打这个电话之前,您知道要检索的艺术家总数吗?如果您之前知道大小,那么使用
Observable.range(0,ARTIST_SIZE).buffer(YOUR_LIMIT)可以轻松检索 -
@AkbarShaEbrahim 您不仅没有阅读我的问题,其中明确指出此示例为 119。您不仅忽略了我指定基于光标的分页 - 这意味着您永远不知道总数.最糟糕的是,你给了我一个我在问题本身中链接的答案。什么都不感谢。
-
看看我的回答应该对你有帮助。
标签: java pagination retrofit rx-java retrofit2