80

In RxJava 1, there was CompositeSubscription, but that is not present in RxJava2, There is something CompositeDisposable in rxJava2. How do I use CompositeDisposable or Disposable in RxJava2?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
anand gaurav
  • 915
  • 2
  • 7
  • 9

3 Answers3

148
private final CompositeDisposable disposables = new CompositeDisposable();


// adding an Observable to the disposable
disposables.add(sampleObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {
                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String value) {
                    }
                }));

    static Observable<String> sampleObservable() {
        return Observable.defer(new Callable<ObservableSource<? extends String>>() {
            @Override
            public ObservableSource<? extends String> call() throws Exception {
                // Do some long running operation
                SystemClock.sleep(2000);
                return Observable.just("one", "two", "three", "four", "five");
            }
        });
    }                


// Using clear will clear all, but can accept new disposable
disposables.clear(); 
// Using dispose will clear all and set isDisposed = true, so it will not accept any new disposable
disposables.dispose(); 

Reference article

Amit Shekhar
  • 3,135
  • 2
  • 16
  • 17
  • 7
    Why they removed subscription? – anand gaurav Aug 29 '16 at 10:51
  • 3
    @anandgaurav : They have written rxJava2 from scratch so they have created better apis. – Amit Shekhar Aug 29 '16 at 10:52
  • you can also use fromCallable instead of defer – shakil.k Nov 05 '16 at 08:40
  • 1
    @anandgaurav The subscription is now used by the streams and serving another purpose. The old Subscription is now Disposable. – loshkin Jan 11 '17 at 15:25
  • @AmitShekhar only DisposableLambdaObserver is showing as a suggestion in subscribeWith. – pa1pal Feb 08 '17 at 10:53
  • @pa1pal I have a running example, it would be great if you try this – Amit Shekhar Feb 08 '17 at 12:23
  • https://github.com/amitshekhariitbhu/RxJava2-Android-Samples/blob/master/app/src/main/java/com/rxjava2/android/samples/ui/operators/DisposableExampleActivity.java – Amit Shekhar Feb 08 '17 at 12:23
  • Hello. I have one question regarding to your library https://github.com/amitshekhariitbhu/Fast-Android-Networking @AmitShekhar –  Mar 07 '17 at 08:08
  • Will your library working fine if i would be uploaded more than 20 images? Will it be hanged my app or asynchronously upload the images?@AmitShekhar –  Mar 09 '17 at 13:05
  • @PiyushGupta: it will upload all asynchronously. – Amit Shekhar Mar 10 '17 at 03:25
  • if (compositeDisposable != null && compositeDisposable.isDisposed()) { compositeDisposable.dispose(); } – Mladen Rakonjac Mar 23 '17 at 13:15
  • Hi @AmitShekhar it would be great if you can help me with that ?and if i am dealing with AsyncTask ,which Observable i should make use of ?Which Observable should i use and when i should i use? – Trinadh Koya Jun 22 '17 at 17:55
  • @amit could you please help me out with how to make get and post request with api using rx java. I have seen your sample . its awsome . Suppose---baseurl/user id and password as a string need to pass . and for registration need to make post with json object . I would appreciate if i get any help for both. just post me syntax with CompositeDisposable – Chayan Chowdhury Aug 16 '17 at 15:07
  • thanks a lot. but is this github libraies stable. i hope its wrapper of RX java . but can i usein my project. – Chayan Chowdhury Aug 17 '17 at 10:01
  • @MladenRakonjac Your comment should be an answer and not a comment itself. Oh, and by the way: your logic is wrong. – mradzinski Nov 02 '17 at 02:45
  • 1
    @AmitShekhar Great comments about the difference between `.clear()` and `.dispose()`! I did not know that using dispose() `will not accept any new disposable` – Kenny Sexton Sep 17 '21 at 21:08
4

CompositeDisposable cannot be reused after being disposed. If you want sync disposable lifecycle with Android Activity lifecycle, it is possible to correspond by making a simple wrapper.

class AndroidDisposable {
    private var compositeDisposable: CompositeDisposable? = null

    fun add(disposable: Disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable?.add(disposable)
    }

    fun dispose() {
        compositeDisposable?.dispose()
        compositeDisposable = null
    }
}

How to use:

class MainActivity : AppCompatActivity() {
    private disposable = AndroidDisposable()

    override fun onStart() {
        super.onStart()
        disposable.add(/* Some disposable */)
    }

    override fun onStop() {
        disposable.dispose()
        super.onStop()
    }
}
Nirro
  • 746
  • 4
  • 18
Seroj Grigoryan
  • 159
  • 1
  • 2
-7
// clearing or unsubscibing
  disposables.clear(); 

this place use dispose()

孔维生
  • 3
  • 1
  • 22
    This is not a good advice, since you cannot resubscribe to an observable after dispose(). – box Jun 29 '17 at 15:05