2016-09-09 38 views
0

我有以下代碼從互聯網獲取項目列表。從Observable獲取前5個項目,從網絡調用獲取數據

Observable<RealmList<Artist>> popArtists = restInterface.getArtists(); 
    compositeSubscription.add(popArtists.subscribeOn(Schedulers.io()) 
    .observeOn(AndroidSchedulers.mainThread()).subscribe(artistsObserver)); 

麻煩的是列表中有超過80個項目,我只希望拿到第5個項目。達到此目的的最佳方法是什麼?

+0

沒有終點,讓您指定限制或頁面大小? – Blackbelt

+2

'拿(5)'在Observable上? –

+0

@ cricket_007'take(5)'工作。謝謝。 –

回答

3

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); 
0

我猜你有過服務器端的控制權,因此解決辦法是先取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));