Composite disposable makes disposing (think cancelling early) easier. Say you have an activity that has multiple api calls happening at once:
var disposable = api.call1(arg1, arg2).subscribe(...)
var disposable2 = api.call2(arg1).subscribe(...)
var disposable3 = api.call3().subscribe()
If you need to prematurely dispose (e.g. the user navigating away from the activity) then you’d need to do this:
disposable.dispose()
disposable2.dispose()
disposable3.dispose()
If you instead use a CompositeDisposable you can store all of the disposables in it. Like so:
val composite = CompositeDisposable()
composite.add(api.call1(arg1, arg2).subscribe(...))
composite.add(api.call2(arg1).subscribe(...))
composite.add(api.call3().subscribe())
And then you can make one dispose call instead:
composite.dispose()
If you are using kotlin you can use operator overloading to make this look nicer:
operator fun CompositeDisposable.plusAssign(disposable: Disposable) {
this.add(disposable)
}
Which enables you to express it as:
val composite = CompositeDisposable()
composite += api.call1(arg1, arg2).subscribe(...)
composite += api.call2(arg1).subscribe(...)
composite += api.call3().subscribe()
Disposable signifies a request (think work being done) and has a method called dispose for disposing of the request.