如何使用RxJava从改进2中获取多个API的数据

时间:2017-05-08 17:25:53

标签: android retrofit2 rx-java2

我是RxJava的新手。我想从JSON API获取数据。假设有两个API,API 1和API 2.我们获取一个JSON对象" mediaId"来自API 1.现在,我想用#34; mediaId"从API 2中获取JSON。如何使用RxJava实现这一点,以及在Android中进行改造?

public void gettdata(final Listerner listerner){

    postitemses= new ArrayList<>();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://www.mytrendin.com")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    APiService networkAPI = retrofit.create(APiService.class);

    Observable<List<Postitems>> observable = networkAPI.getFriendObservable()
                                     .subscribeOn(Schedulers.newThread())
                                     .observeOn(AndroidSchedulers.mainThread());

    observable.subscribe(new Observer<List<Postitems>>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

            listerner.onFailure("oops... Something went wrong");
        }

        @Override
        public void onNext(List<Postitems> postitemsList1) {

            Postitems postitems;
            for (int i=0;i<postitemsList1.size();i++){
                postitems = new Postitems();
                int id = postitemsList1.get(i).getId();
                String title = postitemsList1.get(i).getTitle().getRendered();
                String shortdesc= postitemsList1.get(i).getExcerpt().getRendered();
                String mediaid= postitemsList1.get(i).getFeatured_media();
                String authorid= postitemsList1.get(i).getAuthor();
                String date = postitemsList1.get(i).getDate();
                String slug = postitemsList1.get(i).getSlug();
                Log.i("Hello-slug",""+slug);
                String[] mediaurl= mydata(mediaid);
                Log.i("Hello-mediaurl",""+mediaurl);
                postitems.setId(id);
                postitems.setDate(date);
                postitems.setSlug(""+slug);
                postitems.setPostExcerpt(shortdesc);
                postitems.setPostTitle(title);
                postitemses.add(postitems);

            }
            listerner.showpostitems(postitemses);

        }
    });


}




public String[] mydata(String mediaid){


    final String[] mediaurl = new String[1];
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://www.mytrendin.com")
            .build();
    APiService aPiService = retrofit.create(APiService.class);
    Call<Postitems> call = aPiService.getmediaurl(mediaid);
    call.enqueue(new Callback<Postitems>() {
        @Override
        public void onResponse(Call<Postitems> call, Response<Postitems> response) {

            Postitems postitemsList1 = response.body();
            mediaurl[0] =postitemsList1.getGuid().getRendered();
           // mediaurl[0][0] =postitemsList1.get(0).getGuid().getRendered();
        }

        @Override
        public void onFailure(Call<Postitems> call, Throwable t) {

        }
    });

    return mediaurl;

}

发生

错误

https://www.mytrendin.com 05-09 03:42:09.227 15315-15315 /? D / AndroidRuntime:关闭VM

                                           --------- beginning of crash

05-09 03:42:09.228 15315-15315 /? E / AndroidRuntime:致命异常:主要                                                过程:com.mytrendin.mytrendin,PID:15315                                                java.lang.NullPointerException:尝试调用虚方法.mytrendin.dashboard.utils.Po stitems $ Guid(ZygoteInit.java:755)

1 个答案:

答案 0 :(得分:0)

当然可以将合并运算符与IO调度程序一起使用。通过合并可以将多个Observable合并为一个例子,这是一个例子,

Observable<Integer> odds = Observable.just(1, 3, 5).subscribeOn(someScheduler);
Observable<Integer> evens = Observable.just(2, 4, 6);

Observable.merge(odds, evens)
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });

输出:

下一个:1

下一篇:3

下一篇:5

下一个:2

下一个:4

下一篇:6

序列完成。

在你的情况下是这样的,

public Observable<Data> getMergedData() {
  return Observable.merge(
    networkRepository.getData().subscribeOn(Schedulers.io()),
    networkRepository.getData().subscribeOn(Schedulers.io())
  );
}
  

好的还有另一种解决方法,首先为两个API创建一个observable,然后订阅并观察第一个API订阅的更改。接下来创建一个PublishSubject实例。这很有用,因为一旦观察者订阅了,就会向订阅者发出所有后来观察到的项目。例如,从api响应中发布字符串值。

private PublishSubject<String> subject = PublishSubject.create();


subject.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).filter((s) -> s.size() > 0).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String str) {


            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

然后从主题触发onNext的可观察调用。

subject.onNext("some data from api");

优点,非常灵活地适应班级范围内的任何地方。

希望这有帮助。

以下代码段

  call.enqueue(new Callback<Postitems>() {
        @Override
        public void onResponse(Call<Postitems> call, Response<Postitems> response) {

            Postitems postitemsList1 = response.body();
            mediaurl[0] =postitemsList1.getGuid().getRendered();
           // mediaurl[0][0] =postitemsList1.get(0).getGuid().getRendered();
//use the concept of publish subject here, which i detailed in answer, example
subject.onNext(postitemsList1.getGuid().getRendered());
//the string data will be passed to the above observable for the subject instance.
        }

        @Override
        public void onFailure(Call<Postitems> call, Throwable t) {

        }
    });