0

I am fetching data from the server using multiple api calls for that I am using Retrofit@ and RxJava2.In my api service class I have 2 get requests and they both are running separately due to which data is not coming altogether.I want to fetch all the data fetch together from both apis.Currently I am fetching data something like this and I want some better approach to handle multiple api calls.

Below is my code:

ApiService.class

public interface ApiService {

@GET("Categoery_api")
Observable<List<MenuModel>> getData();

@GET("Recent_six_post_api")
Observable<List<FlashStoryModel>> getFlashStory();

}

MainActivity.java

 private void getMenu(){

    Retrofit retrofit = RetrofitClient.getInstance();
    ApiService myApi = retrofit.create(ApiService.class);

    myApi.getData().subscribeOn(Schedulers.io())
                   .observeOn(AndroidSchedulers.mainThread())
                   .subscribe(new Observer<List<MenuModel>>() {
                       @Override
                       public void onSubscribe(Disposable d) {

                       }

                       @Override
                       public void onNext(List<MenuModel> menuModels) {

                           if(menuModels.size() > 0){

                               menuProg.setVisibility(View.INVISIBLE);
                               list.addAll(menuModels);

                               adapter = new MenuAdapter(list,getApplicationContext());
                               menuRecycler.setAdapter(adapter);
                           }
                       }

                       @Override
                       public void onError(Throwable e) {

                           menuProg.setVisibility(View.INVISIBLE);
                           Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                       }

                       @Override
                       public void onComplete() {

                       }
                   });
}

private void getFlashStory(){

    Retrofit retrofit = RetrofitClient.getInstance();
    ApiService apiService = retrofit.create(ApiService.class);
    apiService.getFlashStory().subscribeOn(Schedulers.io())
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribe(new Observer<List<FlashStoryModel>>() {
                                  @Override
                                  public void onSubscribe(Disposable d) {

                                  }

                                  @Override
                                  public void onNext(List<FlashStoryModel> flashStoryModels) {

                                      if(flashStoryModels.size() > 0){

                                          prog1.setVisibility(View.INVISIBLE);

                                          storyList.addAll(flashStoryModels);
                                          flashStoryAdapter = new FlashStoryAdapter(getActivity(),storyList);
                                          flashStory.setAdapter(flashStoryAdapter);

                                          final Handler handler = new Handler();
                                          final Runnable update = new Runnable() {
                                              @Override
                                              public void run() {
                                                  if (currentPage == 6) {
                                                      currentPage = 0;
                                                  }
                                                  flashStory.setCurrentItem(currentPage++, true);
                                              }
                                          };

                                          timer = new Timer(); // This will create a new Thread
                                          timer.schedule(new TimerTask() { // task to be scheduled
                                              @Override
                                              public void run() {
                                                  handler.post(update);
                                              }
                                          }, DELAY_MS, PERIOD_MS);

                                      }
                                  }

                                  @Override
                                  public void onError(Throwable e) {

                                      prog1.setVisibility(View.INVISIBLE);
                                      Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
                                  }

                                  @Override
                                  public void onComplete() {

                                  }
                              });
}

Someone please let me know how can I achieve desired result.Any help would be appreciated.

THANKS

Digvijay
  • 2,887
  • 3
  • 36
  • 86
  • 1
    You should use Rxjava [zip](https://stackoverflow.com/questions/30219877/rxjava-android-how-to-use-the-zip-operator) operator – Manohar Mar 03 '20 at 06:28

2 Answers2

1

Use Observable.zip(...)

Observable.zip(
    apiService.getFlashStory(),
    apiService.getData(),
    BiFunction< List<FlashStoryModel>, List<MenuModel>, Unit> { r1, r2, _ ->
        // r1 is result from apiService.getFlashStory()
        // r2 is result from apiService.getData()

        // Do something here.

        // For example, this is what your code do above for apiService.getData()
        if(r2.size() > 0){
            menuProg.setVisibility(View.INVISIBLE);
            list.addAll(r2);

            adapter = new MenuAdapter(list,getApplicationContext());
            menuRecycler.setAdapter(adapter);
        }

    }

).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

This is actual BiFunction.

object: BiFunction<P, Q, R> {
    override fun apply(t1: P, t2: Q): R {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

But I write it as.

BiFunction<P, Q, R> { r1, r2, returnValue -> 
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
Hello World
  • 740
  • 5
  • 18
0

you can call at the same time but with starting new thread, Dont use main thread for this purpose. myApi.getData().subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.newThread())

this way you can avoid application hang or avoid lagging.

Irfan Yaqub
  • 140
  • 10