In real development, page closing and cancellation requests are common requirements, and here is a simple implementation. My idea is to tie the network request to the lifecycle of the context. Rxjava’s Subject is used here, which is both an Observable and an Observer. You can send and receive messages.

I started by defining several enumerations that correspond to the lifecycle of the context.

public enum ActivityLifeCycleEvent {
    CREATE,START,RESUME,PAUSE,STOP,DESTROY
}
Copy the code

Taking fragments as an example, in baseFragments, messages are emitted in the corresponding lifecycle callback.


import rx.subjects.PublishSubject;

public abstract class BaseFragment extends Fragment {

    protected final PublishSubject<ActivityLifeCycleEvent> lifecycleSubject = PublishSubject.create();



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        lifecycleSubject.onNext(ActivityLifeCycleEvent.PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        lifecycleSubject.onNext(ActivityLifeCycleEvent.STOP);
    }


    @Override
    public void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityLifeCycleEvent.RESUME);
    }


    @Override
    public void onDestroy() { super.onDestroy(); lifecycleSubject.onNext(ActivityLifeCycleEvent.DESTROY); }}Copy the code

Typically we use Retrofit+Rxjava for network requests, such as the following:

@Multipart
@POST(Urls.TIMER_GETUSERDETAIL_RX)
Observable<Results<User>> getUser(@PartMap Map<String, RequestBody> map);
Copy the code

The specific request might look something like this

ApiService.instancce()
  .getUser(p.build())
  .takeUntil(bindLifeCycle (lifecycleSubject, ActivityLifeCycleEvent. DESTROY).) the subscribe ({... })Copy the code

Note: The following sentence

.takeUntil(RxUtils.bindLifeCycle(lifecycleSubject, ActivityLifeCycleEvent.DESTROY))
Copy the code

TakeUntil If the response is successful it automatically terminates the source Observable and stops sending data to the back end. If not, continue sending the request. Here if you receive ActivityLifeCycleEvent. DESTROY message, will stop backend sending data.

 public static Observable<ActivityLifeCycleEvent> bindLifeCycle(PublishSubject<ActivityLifeCycleEvent> lifecycleSubject, ActivityLifeCycleEvent bindEvent) {
        return  lifecycleSubject.takeFirst(activityLifeCycleEvent -> activityLifeCycleEvent.equals(bindEvent));
    }
Copy the code

Well, that’s all. Here’s how to use it happily

This method only cancels subsequent operations after receiving network data, but does not actually stop the current request