使用Retrofit2

时间:2016-07-13 18:01:31

标签: java android rx-java rx-android

所以我使用自定义Google搜索API来获取数据集中每个名称参数的图片网址。

我想在对Retrofit2的API调用中迭代数据集中的每个名称作为查询参数。

public interface GoogleImageAPI {
    @GET("v1?key=MyAPIKEY&cx=MyCustomSearchID&searchType=image&fileType=jpg&imgSize=large&alt=json")
    Observable<Photos> loadPhotos(@Query("q") String artistQuery);
}

到目前为止,我已经构建了Retrofit适配器和API实例来返回一个Observable:

public Observable<Photos> getPhotosObservable(String artistName){
    Retrofit retrofit = new Retrofit.Builder()
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://www.googleapis.com/customsearch/")
            .build();
    GoogleImageAPI googleImageAPI = retrofit.create(GoogleImageAPI.class);
    return googleImageAPI.loadPhotos(artistName.replace(" ","+"));
}

我有一个getPhotos(String name)方法,它创建一个observable并订阅它。我可以使用测试参数iegetPhotos(“rocket”)运行此方法,并返回一个Photos对象,其中包含“火箭”前10个Google照片搜索结果的列表

public void getPhotos(String artistName){
    Observable<Photos> photosObservable = mDataManager.getPhotosObservable(artistName);
    Subscription subscription = photosObservable.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<Photos>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if(e instanceof HttpException){
                    HttpException response = (HttpException)e;
                    Log.i(TAG,"bad response: "+response.code());
                }
            }

            @Override
            public void onNext(Photos photos) {
                Photos mPhotos = photos;
                Log.i(TAG,"size: "+mPhotos);
            }
        });
}

是否有一种安全/正确的迭代方法,因此调用API 100次而不会耗尽内存或创建100个可观察量?

例如,我可以这样做吗?这看起来非常耗费资源:

for(String name : artistNames){
    googleImageAPI.loadPhotos(name.replace(" ","+"))
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<Github>() {
        @Override
        public final void onCompleted() {
            // do nothing
        }

        @Override
        public final void onError(Throwable e) {
            Log.e("GithubDemo", e.getMessage());
        }

        @Override
        public final void onNext(Github response) {
            mCardAdapter.addData(response);
        }
    });
}

编辑(工作示例),生成Photo对象的组合列表:

public void getPhotos(){
    mDataManager.getArtists()
        .subscribeOn(Schedulers.io())
        .subscribe(new Action1<JSONArray>() {
            @Override
            public void call(JSONArray jsonArray) {
                LinkedHashMap<Integer,Artist> artistMap = presentArtists(jsonArray);
                Collection<Artist> artists = artistMap.values();
                Observable.from(artists)
                   .map(new Func1<Artist, String>() {
                       @Override
                       public String call(Artist artist) {
                           String artistName;
                           if(artist.getName().contains("(")){
                               artistName = artist.getName().substring(0,artist.getName().indexOf("(")-2).replace(" ","+");
                           }else {
                               artistName = artist.getName().replace(" ", "+");
                           }
                           return artistName;
                       }
                   })
                    .flatMap(new Func1<String, Observable<Photos>>() {
                        @Override
                        public Observable<Photos> call(String artistName) {
                           return mDataManager.getPhotosObservable(artistName);
                        }
                    })
                    .toList()
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<List<Photos>>() {
                        @Override
                        public void onCompleted() {}

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(List<Photos> objects) {
                            mDataManager.savePhotos(objects);
                        }
                    });
            }
        });
}

1 个答案:

答案 0 :(得分:3)

您可以这样做:

    Observable.from(artistNames)
            .map(name -> name.replace(" ", "+"))
            .flatMap(name -> googleImageAPI.loadPhotos(name))
            .toList()
            .subscribe(new Subscriber<List<Github>>() {
                @Override
                public final void onCompleted() {
                    // do nothing
                }

                @Override
                public final void onError(Throwable e) {
                    Log.e("GithubDemo", e.getMessage());
                }

                @Override
                public final void onNext(List<Github> response) {
                    mCardAdapter.addAll(response);
                }
            })

Observable创建List。使用map运算符替换带有加号的空格。使用flatMap来调用API。使用toList创建所有回复的列表。然后,您可以将addAll的所有响应添加到适配器。