Multiple ways to unsubscribe from Dispose in RxJava2 (source code Analysis)

Source: Internet
Author: User
Tags throwable

GitHub related code: GitHub address

Always feel RxJava2 unsubscribe a bit chaotic, so also can cancel, that also can cancel, failed to system up feel like fell into the spider web Cave, confused ...
Here are a few things to say.

Several cases of cancellation
    1. Subscribe returned the disposable:

    2. Subscribe does not return disposable, obtained from the ONSUBSCRIBE of Observer:

    3. Previously viewed from the Internet, using the inherited Disposableobserver Observer, this observer can be directly dispose

SOURCE Analysis

wordy what Ah, such a simple thing also need to paste source code?
Big Brother, the following summary ....

From the first case, we went into the look .subscribe((s) -> {}) and found that it was an overloaded method that returned a four-parameter

   Public Final disposable subscribe (CONSUMER<? Super t> onNext) {        return  Subscribe (OnNext, functions.on_error_missing, Functions.empty_action, Functions.emptyconsumer ());    }
 Public Final disposable subscribe (CONSUMER<? super t> OnNext, consumer<? Super Throwable>  OnError,            Action oncomplete, Consumer<? Super disposable> onsubscribe) {        ...        LambdaobserverNew lambdaobserver<t>(OnNext, OnError, OnComplete, onsubscribe);        Subscribe (LS);         return ls;    }

As you can see, this method creates one LambdaObserver , which Observer implements the Disposable interface, so it can be Disposable returned directly to the most superior, which is why the first case subscribe can be returned disposable .

 Public class Lambdaobserver<t> extends atomicreference<disposable>        implements Observer<T>, Disposable, Lambdaconsumerintrospection {...            }

And the second case is actually the one in subscribe the above method.subscribe(LambdaObserver)

   PublicFinalvoidSubscribe (observer<? Super T>observer) {OBJECTHELPER.REQUIRENONNULL (Observer,"Observer is null"); Try{Observer= Rxjavaplugins.onsubscribe ( This, observer); OBJECTHELPER.REQUIRENONNULL (Observer,"Plugin returned null Observer");        SUBSCRIBEACTUAL (Observer); } Catch(NullPointerException e) {//NOPMD            Throwe; } Catch(Throwable e) {exceptions.throwiffatal (e); //can ' t call OnError because no-know if a disposable have been set or not//can ' t call Onsubscribe because the call might has set a Subscription alreadyRxjavaplugins.onerror (e); NullPointerException NPE=NewNullPointerException ("actually not, but can ' t throw other exceptions due to RS");            Npe.initcause (e); ThrowNPE; }    }

This method executes an subscribeActual(observer) abstract method, which is given Observale to the subclass rewrite.

The third situation appears to DisposableObserver LambdaObserver be similar, or even simpler

 Public Abstract classDisposableobserver<t> Implements Observer<t>, Disposable {final atomicreference<Disposable> s =NewAtomicreference<disposable>(); @Override PublicFinalvoidOnsubscribe (@NonNull disposable s) {if(Endconsumerhelper.setonce ( This. S, S, GetClass ()))        {OnStart (); }    }    protected voidOnStart () {} @Override PublicFinal Boolean isdisposed () {returnS.Get() ==disposablehelper.disposed; } @Override PublicFinalvoidDispose () {disposablehelper.dispose (s); }}
Brief summary

A little bit, we understand that when the Observer four methods of the incoming interface are subscribe built in, and LambdaObserver this and the LambdaObserver third case DisposableObserver are implemented Disposable interface, so can be Disposable returned, it is so simple.

In the third case CompositeDisposable , it is simply a Disposable collection (Openhashset maintenance, thread safety, provided internally by RxJava) that CompositeDisposable.dispose() iterates through all the internal Disposable execution dispose .

/** Dispose The contents of the Openhashset by suppressing non-fatal * throwables till the end. * @param set the Openhashset to dispose elements of*/    voidDispose (openhashset<disposable>Set) {        ...         for(Object o:array) {if(o instanceof disposable) {Try{(disposable) O). Dispose (); } Catch(Throwable ex) {exceptions.throwiffatal (ex); if(Errors = =NULL) {Errors=NewArraylist<throwable>();                } errors.add (ex); }            }        }        ...    }
Application of several methods
    1. If it is used sporadically, the first of the most convenient, observer four methods can be used on demand, the same logical method has a variety of options to choose

    2. If you use a Observer lot of common logic, you can write an BaseObserver inheritance DisposableObserver or LambdaObserver , directly usingxxObserver.dispose()

      • class Baseobserver<t> (): Disposableobserver<t> ()
    3. If you have a lot diposable to cancel, it CompositeDisposable will be easier to use.

How to automatically unsubscribe in MVP to avoid memory leaks, there is a sample GitHub address in my GitHub package

Multiple ways to unsubscribe from Dispose in RxJava2 (source code Analysis)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.