Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit & RxJava multiple requests complete

I need to do:

  1. Request 2 lists of news from different websites
  2. Combine results from requests
  3. Sort items by date
  4. Get 10 newest news
  5. Save them
  6. Show complete message

For example, I have this two observables:

Observable<RegionalNews> regionalNews;
Observable<NationalNews> nationalNews;

public interface NewsNationalService {
  @GET("news/national")
  Observable<News> getNationalNews();
}

public interface NewsRegionalService {
  @GET("news/regional")
  Observable<News> getRegionalNews();
}
like image 529
Vyacheslav Martynenko Avatar asked Apr 18 '17 09:04

Vyacheslav Martynenko


2 Answers

If you don't want to do something specific with the combined results, then merge() is enough:

Observable<RegionalNews> regionalNews = ...;
Observable<NationalNews> nationalNews = ...;

Observable
.merge(regionalNews, nationalNews)
.ignoreElements()
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(() -> { /* show alert */ })
.subscribe()
like image 121
Tassos Bassoukos Avatar answered Oct 21 '22 15:10

Tassos Bassoukos


You can use zip operator to call 2 requests async and save or process their data on response.

For example.

Below are two Observable

Observable<ResponseOne> responseOneObservable = getRetrofitClient().getDataOne()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());

Observable<ResponseTwo> responseTwoObservable = getRetrofitClient().getDataTwo()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());

Using zip operator on above two Observable as below.

Observable<ArrayList<TestData>> testDataObservable = Observable.zip(responseOneObservable, responseTwoObservable, new Func2<ResponseOne, ResponseTwo, ArrayList<TestData>>() {
            @Override
                public ArrayList<TestData> call(ResponseOne responseOne, ResponseTwo responseTwo) {
                  ArrayList<TestData> testDataList = new ArrayList();
                      // process data from response responseOne & responseTwo
                  return testDataList;
            } 
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Subscriber<ArrayList<TestData>>() {

        @Override
        public void onNext(ArrayList<TestData> testDataList) {

        }

        @Override
        public void onCompleted() {
            Log.d(TAG, "onCompleted" ); 
            // you can show alert here or do something when completed 
        }

        @Override
        public void onError(Throwable t) {
            Log.d(TAG, "onError Throwable: " + t.toString() );
        }
    });
like image 11
Priyank Patel Avatar answered Oct 21 '22 15:10

Priyank Patel