Khoa Tran
Khoa Tran

Reputation: 538

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?

Upvotes: 0

Views: 193

Answers (2)

Kiskae
Kiskae

Reputation: 25603

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);
}

Upvotes: 1

elmorabea
elmorabea

Reputation: 3263

About your first Subscription, when your data is loaded and the onComplete() method is called, this Subscription is automatically unsubscribed.

About the pull to refresh, i don't know how you are implementing that, but for example the Android RefreshLayout, disables calling the refresh callback, unless the previous refresh has ended. So maybe you can do that.

If you actually want to have multiple refresh events, then i suggest you unsubscribe the old refreshing subscription if it exists before making a new one.

Upvotes: 1

Related Questions