Search code examples
javaandroidreactivex

Add more Subscription when pull to refresh with Reactive Android


I wrote code to get data from server and display to list view. And I also add pull to refresh feature. I wonder if we add more subscription when pull to refresh is called so is it best practice or should I unsubscribe before I add the new one?

CompositeSubscription mSubscription = new CompositeSubscription();
private void pullToRefresh() {
  Subscription subscription = mMatchingApi.getRequest(new GetRequest(
            new GetRequest.Builder().setRequestIds(orderIds)))
            .subscribe(new Subscriber<GetRequestResponse>() {
               //update list
                }
            });
     mSubscription.add(subscription);
}

I also clear subscription in onDestroy

   @Override
   public void onDestroy() {
    if (mSubscription != null) {
        mSubscription.clear();
     }
   }

So example if I call function pullToRefresh() more than once time (two or three time). eg:

result 1 = pullToRefresh();
result 2 = pullToRefresh();
result 3 = pullToRefresh();

So if result 1 is not complete yet and result 2 complete before result 1. Then the data of list will display wrong? (display with result 1 but it should display with result 2) Should I clear subscription 1 before add a new one?


Solution

  • Use a separate SerialSubscription to keep only the latest request alive:

    CompositeSubscription mSubscription = new CompositeSubscription();
    SerialSubscription mPullRequest = new SerialSubscription();
    
    {
        mSubscription.add(mPullRequest); // Stop all requests if mSubscription is unsubscribed
    }
    
    private void pullToRefresh() {
        /* same code as before */
        mPullRequest.set(subscription);
    }