Skip to content

Instantly share code, notes, and snippets.

@captswag
Created November 12, 2017 09:31
Show Gist options
  • Save captswag/68fbc0b1fe26c7db8766bf222339ea71 to your computer and use it in GitHub Desktop.
Save captswag/68fbc0b1fe26c7db8766bf222339ea71 to your computer and use it in GitHub Desktop.
void fetchTopTrendingList() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.SERVER_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
final HackerNewsInterface hackerNewsInterface = retrofit.create(HackerNewsInterface.class);
List<Observable<StoryResponse>> storyResponseListObservable = hackerNewsInterface.getTopTrendingList()
.subscribeOn(Schedulers.io())
.map(new Function<List<Integer>, List<Observable<StoryResponse>>>() {
@Override
public List<Observable<StoryResponse>> apply(List<Integer> ids) throws Exception {
List<Observable<StoryResponse>> storyResponseListObservable = new ArrayList<>();
int listLimit = ids.size() < 10 ? ids.size() : 10;
for (int i = 0; i < listLimit; i++) {
storyResponseListObservable.add(hackerNewsInterface.getStory(ids.get(i)));
}
return storyResponseListObservable;
}
}).blockingSingle();
Observable.zip(storyResponseListObservable, new Function<Object[], List<StoryResponse>>() {
@Override
public List<StoryResponse> apply(Object[] objects) throws Exception {
List<StoryResponse> storyResponseList = new ArrayList<>();
for (Object object : objects) {
if (object instanceof StoryResponse) {
storyResponseList.add((StoryResponse) object);
}
}
return storyResponseList;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<StoryResponse>>() {
@Override
public void accept(List<StoryResponse> storyResponses) throws Exception {
try {
mStoryListView.populateStoryList(storyResponses);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment