从网络调用中获取数据的 Observable 获取前 5 个项目
Getting First 5 Items from Observable that fetches data from a network call
我有以下代码可以从互联网上获取项目列表。
Observable<RealmList<Artist>> popArtists = restInterface.getArtists();
compositeSubscription.add(popArtists.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(artistsObserver));
问题是列表有 80 多个项目,我只想获取前 5 个项目。实现此目标的最佳方法是什么?
我猜你无法控制服务器端,所以解决方案是从收到的结果中取出前 5 项:
Observable<RealmList<Artist>> popArtists = restInterface.getArtists();
compositeSubscription.add(
popArtists.flatMap(list-> Observable.from(list).limit(5)).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(artistsObserver));
take
是您要找的接线员。 (请参阅此处的文档:http://reactivex.io/documentation/operators/take.html)
flatMapIterable
将您的 RealmList
(实现 Iterable
,这就是可以使用 flatMapIterable
的原因)转换为发出所有项目的 Observable
你的名单
Subscription subscription = restInterface.getArtists()
.flatMapIterable(l -> l)
.take(5)
.subscribeOn(Schedulers.io())
.observeOn(androidSchedulers.mainThread())
.subscribe(artistsObserver);
compositeSubscription.add(subscription);
我有以下代码可以从互联网上获取项目列表。
Observable<RealmList<Artist>> popArtists = restInterface.getArtists();
compositeSubscription.add(popArtists.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(artistsObserver));
问题是列表有 80 多个项目,我只想获取前 5 个项目。实现此目标的最佳方法是什么?
我猜你无法控制服务器端,所以解决方案是从收到的结果中取出前 5 项:
Observable<RealmList<Artist>> popArtists = restInterface.getArtists();
compositeSubscription.add(
popArtists.flatMap(list-> Observable.from(list).limit(5)).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(artistsObserver));
take
是您要找的接线员。 (请参阅此处的文档:http://reactivex.io/documentation/operators/take.html)
flatMapIterable
将您的 RealmList
(实现 Iterable
,这就是可以使用 flatMapIterable
的原因)转换为发出所有项目的 Observable
你的名单
Subscription subscription = restInterface.getArtists()
.flatMapIterable(l -> l)
.take(5)
.subscribeOn(Schedulers.io())
.observeOn(androidSchedulers.mainThread())
.subscribe(artistsObserver);
compositeSubscription.add(subscription);