Skip to content

Instantly share code, notes, and snippets.

Created March 27, 2017 04:26
Show Gist options
  • Save anonymous/1d4468faa5611d4a0fbb2ab3f8667527 to your computer and use it in GitHub Desktop.
Save anonymous/1d4468faa5611d4a0fbb2ab3f8667527 to your computer and use it in GitHub Desktop.
Rx Retrofit Calls
public class PictureNetworkService implements PresenterModelContract.Model {
private static final String TAG = "PictureGrabber";
private final MainPresenter mMainPresenter;
//My Retrofit calls are now wrapped as an RX observable
private FlickrObservableService mFlickrObservableService;
private GiphyObservableService mGiphyObservableService;
Observable<ArrayList<String>> mCombinedObservable;
public PictureNetworkService(MainPresenter mainPresenter) {
mMainPresenter = mainPresenter;
mFlickrObservableService = ApiUtils.getFlickrService();
mGiphyObservableService = ApiUtils.getGiphyService();
}
public void networkApiRequestPictures(String searchTerm) {
//Create my zip observable which consists of two Retrofit observables
mCombinedObservable = Observable.zip(
mFlickrObservableService.getFlickrAnswers(
ApiUtils.FLICKR_API_KEY,
ApiUtils.FLICKR_FORMAT,
ApiUtils.FLICKR_NOJSONCALLBACK,
ApiUtils.FLICKR_EXTRAS,
ApiUtils.FLICKR_METHOD,
searchTerm),
mGiphyObservableService.getGiphyAnswers(
searchTerm,
ApiUtils.GIPHY_API_KEY),
new BiFunction<FlickrJsonResponse, GiphyJsonResponse, ArrayList<String>>() {
@Override
public ArrayList<String> apply(@NonNull FlickrJsonResponse flickrJsonResponse,
@NonNull GiphyJsonResponse giphyJsonResponse) throws Exception {
Log.i(TAG, "Got both");
ArrayList<String> combinedUrls = new ArrayList<>();
//Pull the URLs from both resources and put them into a single list for our
//adapter to load from.
for(int i=0;i<flickrJsonResponse.getPhotos().getPhoto().size();i++){
combinedUrls.add(flickrJsonResponse.getPhotos().getPhoto().get(i).getUrl_s());
}
for(int i=0;i<giphyJsonResponse.getData().size();i++){
combinedUrls.add(giphyJsonResponse.getData().get(i).getImages().getDownsized().getUrl());
}
//Gets sent to onNext of our zip observer
return combinedUrls;
}
});
//Kick off the search
mCombinedObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(zipObserver());
}
//Handles the return of both Retrofit calls
private Observer<ArrayList<String>> zipObserver() {
return new Observer<ArrayList<String>>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, " onSubscribe : " + d.isDisposed());
}
@Override
public void onNext(ArrayList<String> combinedList) {
mMainPresenter.updatePhotoAdapter(combinedList);
}
@Override
public void onError(Throwable e) {
Log.d(TAG, " onError : ");
}
@Override
public void onComplete() {
Log.d(TAG, " onComplete");
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment